PHP - 查找多维数组之间的差异,但保留索引

时间:2015-01-27 22:27:22

标签: php arrays multidimensional-array

我有两个阵列:

$草堆

Array (
    [rowid] => Array
        (
            [0] => 200
            [1] => 400
            [2] => 500
        )

    [description] => Array
        (
            [0] => text1
            [1] => text2
            [2] => text3
        )

    [qty] => Array
        (
            [0] => 1
            [1] => 20
            [2] => 1
        )

)

$针

Array
(
    [rowid] => Array
        (
            [0] => 200
            [1] => 500
        )

    [description] => Array
        (
            [0] => newtext1
            [1] => newtext3
        )

    [qty] => Array
        (
            [0] => 50
            [1] => 60
        )

)

我想越过haystack数组(带有foreach)并找到hay [" rowid"]在haystack中存在与否的位置。 我想得到这样的东西:

  

Haystack值200描述text1在针中是PRESENT但已修改   在newtext1中,qty = 50(针键0)
  干草堆值400是MISSING
  干草堆值500描述text3在针上是PRESENT但已修改   在newtext3中,qty = 60(针键2)

我试过了:

   foreach ($haystack["rowid"] as $key => $value) :

                $result = recursive_array_search($haystack["rowid"][$key],$needle);

                if ($result) {              
                    //found the same rowid
                }
                else { 
                    //not found 
        }

    function recursive_array_search($needle,$haystack) {
            foreach($haystack as $key=>$value) {
                $current_key=$key;
                if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
                    return array("key" => $current_key, "value" => $value);
                }
            }
            return false; 
    }

但是当$ key = 2(最后$ haystack键)$ result [" value"]或$ result [" key"]变为" null"因为$ needle只有0和1个键! 我该如何编辑这个功能? 非常感谢,我不是多维数组的专家!

1 个答案:

答案 0 :(得分:0)

简单地用新索引$ i解决:)

$i=0;
foreach ($haystack["rowid"] as $key => $value) :

        $result = recursive_array_search($haystack["rowid"][$key],$needle["rowid"]);

        if ($result) {              
            //found new value in $needle["description"][$i]
            $i++;
        }
        else { 
            //not found
}

有快速方法吗?再见