php中的数组差异

时间:2014-01-02 09:15:14

标签: php arrays multidimensional-array

如何区分具有以下结构的两个数组

<?php

$a1 = array("0" => "red");
$a2 = array("0" => "red", "1" => "green", "2" => "blue", "3" => "yellow");
$result = arrayDiff($a1, $a2);
print '<pre>';
print_r($result);
print '</pre>';

function arrayDiff($aArray1, $aArray2) {
    $aReturn = array();

    foreach ($aArray1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $aArray2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayDiff($mValue, $aArray2[$mKey]);
                if (count($aRecursiveDiff)) {
                    $aReturn[$mKey] = $aRecursiveDiff;
                }
            } else {
                if ($mValue != $aArray2[$mKey]) {
                    $aReturn[$mKey] = $aArray2[$mKey];
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }

    return $aReturn;
}

?>

我得到一个空数组作为输出。我的首选输出是:

Array
(
   [0] => green
   [1] => blue
   [2] => yellow   
)

5 个答案:

答案 0 :(得分:6)

<?php
$a1 = array("0" => "red");
$a2 = array("0" => "red", "1" => "green", "2" => "blue", "3" => "yellow");
$result = array_diff($a2, $a1);

    print_r($result);

    $result = array_values($result);
    print_r($result); 
?>

答案 1 :(得分:3)

您可以将array_diff函数用作

$a1 = array("0" => "red");
$a2 = array("0" => "red", "1" => "green", "2" => "blue", "3" => "yellow");
if (sizeof($a1) > sizeof($a2)) {
    $result = array_diff($a1, $a2);
} else {
    $result = array_diff($a2, $a1);
}
print '<pre>';
print_r($result);
print '</pre>';

答案 2 :(得分:1)

订单很重要:

$a1 = array("0" => "red");
$a2 = array("0" => "red", "1" => "green", "2" => "blue", "3" => "yellow");

//First Try :
$result = array_diff($a1, $a2); //Output Empty Array

//2nd Try :
$result = array_diff($a2, $a1); //Output as desired

您应该使用本机PHP函数http://php.net/array_diff

答案 3 :(得分:0)

$a1 = array("0" => "red");
$a2 = array("0" => "red", "1" => "green", "2" => "blue", "3" => "yellow");
$result = array_diff_assoc($a2, $a1);
print '<pre>';
print_r($result);
print '</pre>';

array_diff_assoc - 使用附加索引检查计算数组的差异

答案 4 :(得分:0)

以简单的方式,您可以获得所需的输出:

$a1 = array("0" => "red");
$a2 = array("0" => "red", "1" => "green", "2" => "blue", "3" => "yellow");
foreach($a2 as $val)
{
 if(!(in_array($val,$a1)))
 {
  $result[]=$val; 
 }
}
print_r($result);