多维比较两个数组

时间:2012-06-05 13:34:36

标签: php

我有两个数组

$array1 = array(0=>array('mac'=>'mac0','geo'=>'geo0'),1=>array('mac'=>'mac1','geo'=>'geo1'),
2=>array('mac'=>'mac2','geo'=>'geo2')...);


$array2 = array(0=>array('id'=>'id0','gname'=>'gname0'),1=>array('id'=>'id1','gname'=>'gname1'),
2=>array('id'=>'id2','gname'=>'gname2')...);

我想比较第一个数组值mac和第二个数组值gname

的两个数组

如果gename的值在gname的值中可用,则更新else,请执行note update else do

不更新

例如,

如果数组的值在array2中的任何数组中可用 更新

否则不要更新

1 个答案:

答案 0 :(得分:0)

这里写了代码:

    $array1 = array(0=>array('mac'=>'mac0','geo'=>'geo0'),1=>array('mac'=>'mac1','geo'=>'geo1'),
2=>array('mac'=>'mac2','geo'=>'geo2'));


$array2 = array(0=>array('id'=>'id0','gname'=>'gname0'),1=>array('id'=>'id1','gname'=>'gname1'),
2=>array('id'=>'id2','gname'=>'gname2'));

function gluearray($ar1, $ar2) {
    foreach($ar2 as $key=>$value) {
        if(isset($ar1[$key])) {
            if(is_array($ar1[$key])) {
                $ar1[$key] = gluearray($ar1[$key], $value);
            } else {
                if($ar1[$key]!==$value) {
                    $ar1[$key] = $value;
                }
            }
        } else {
            $ar1[$key] = $value;
        }
    }
    return $ar1;
}
print_r(gluearray($array1, $array2));

结果:

数组([0] =>数组([mac] => mac0 [geo] => geo0 [id] => id0 [gname] => gname0)[1] =>数组( [mac] => mac1 [geo] => geo1 [id] => id1 [gname] => gname1)[2] =>数组([mac] => mac2 [geo] => geo2 [id] => id2 [gname] => gname2))