试图比较两个数组的元素 [英] trying to compare elements of two arrays

查看:58
本文介绍了试图比较两个数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php中有两个数组,我正在使用array_intersect函数查找公共元素,如果存在公共元素,但是问题是有两个公共元素,但是我在这里只得到一个元素是我的代码...

I have two arrays in php and i am using the array_intersect function to find the common elements and if common elements exist but the issue is there are two common elements but i am getting only one element here is my code...

function check_if_exists($company_timings,$in_time) {   
    $length_of_company=sizeof($company_timings);
    $length_of_emp=sizeof($in_time);
    for ($i=0; $i <=$length_of_company-1 ; $i++) { 
        # code...
        for ($j=0; $j <=$length_of_emp-1; $j++) { 
            # code...
            if ($in_time[$j]==$company_timings[$i]) {
                # code...
                $common[]=$company_timings[$i];
                return $common;
            }
        }
     }
 }


推荐答案

按以下步骤操作:

function check_if_exists($company_timings,$in_time) {   
    $length_of_company=sizeof($company_timings);
    $length_of_emp=sizeof($in_time);

    for ($i=0; $i <=$length_of_company-1 ; $i++) { 
        # code...
        for ($j=0; $j <=$length_of_emp-1; $j++) { 
            # code...
            if ($in_time[$j]==$company_timings[$i]) {
                # code...
                $common[]=$company_timings[$i];
            }
        }
     }
     if(count($common) > 0){
         return $common;
     }else{
         // Return else;
     }
 }

或捷径:

$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);

-- Output --
Array
(
    [a] => green
    [0] => red
)

这篇关于试图比较两个数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆