从多维数组中提取值

时间:2010-08-09 19:55:05

标签: php array-difference

我有两个像这样结构的数组

$array1 = Array
 (
     [0] => Array
         (
             ['story_id'] => 47789
         )

     [1] => Array
         (
             ['story_id'] => 47779
         )

     [2] => Array
         (
             ['story_id'] => 47776
         )

     [3] => Array
         (
             ['story_id'] => 47773
         )

     [4] => Array
         (
             ['story_id'] => 47763
         )
 )


$array2 = Array
 (
     [0] => Array
         (
             ['story_id'] => 47789
         )

     [1] => Array
         (
             ['story_id'] => 47777
         )

     [2] => Array
         (
             ['story_id'] => 47776
         )

     [3] => Array
         (
             ['story_id'] => 47773
         )

     [4] => Array
         (
             ['story_id'] => 47763
         )
 )

我希望从array2中获得array1的不同,所以我尝试使用

    $results = array_diff($array1, $array2);

但是它变得空白是否有任何简单的方法可以解决这个问题,或者最好让我把阵列简化下来,如果有的话,那么这样做有简单的方法吗?

1 个答案:

答案 0 :(得分:0)

因为array_diff仅用于1维数组。对于你的2数组,让我们使用来自php.net的一些代码

function multidimensional_array_diff($a1, $a2)
{
$r = array();

foreach ($a2 as $key => $second) {
    foreach ($a1 as $key => $first) {

        if (isset($a2[$key])) {
            foreach ($first as $first_value) {
                foreach ($second as $second_value) {
                    if ($first_value == $second_value) {
                        $true = true;
                        break;
                    }
                }
                if (!isset($true)) {

                    $r[$key][] = $first_value;
                }
                unset($true);
            }
        } else {
            $r[$key] = $first;
        }
    }
}
return $r;
}