PHP比较二维数组

时间:2010-05-30 02:41:05

标签: php arrays compare

我想知道如何比较两个二维数组值。

第一个数组

Array 1
(
    [0] => Array
        (
            [0] => a
        )

    [1] => Array
        (
            [0] => b
        )

    [2] => Array
        (
            [0] => c
        )

}

第二个

Array 2
(
    [0] => Array
        (
            [0] => a
        )

    [1] => Array
        (
            [0] => d
        )

    [2] => Array
        (
            [0] => e
        )

}

我需要使用循环来比较数组并检查匹配的值。在我的例子中,array1 [0] [0] = a匹配array2 [0] [0] = a。如果匹配,php将输出一些html。

我的foreach循环

foreach ($array1 as $arrays){
    foreach($arrays as $array){
      //need to compare array2 here not sure how to do it.
    }
}

2 个答案:

答案 0 :(得分:2)

foreach($array1 as $k1 => $arrays) {
    foreach($arrays as $k2 => $val) {

        if($array2[$k1][$k2] == $val) {
            // $array1[$k1][$k2] is equal to $array2[$k1][$k2]
        }
    }
} // end of foreach

foreach($a as $k => $v)语法与foreach($a as $v)的功能相同,只是它还将与值关联的键放入$k

答案 1 :(得分:1)

您可以使用array_diff_assoclike

if(count(array_diff_assoc($array1,array2) != 0))
{
   //Arrays are not the same
}else{
  echo 'these following items are differing in throughout the arrays . ' . print_r(array_diff_assoc($array1,array2),true);
}

希望这会对你有所帮助。

另请注意array_diff_assoc,它返回的数组项与另一个数组(包括其索引键)不同。