【问题标题】:PHP - Find the differences between multidimensional arrays, but keep the indexPHP - 查找多维数组之间的差异,但保留索引
【发布时间】:2015-03-26 16:50:40
【问题描述】:

我有这两个数组:

$干草堆

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)并找到 needle["rowid"] 存在或不存在于 haystack 中的位置。 我想得到这样的东西:

Haystack 值 200 描述 text1 在 needle 中存在但已修改 在 newtext1 中,数量 = 50(针键 0)
干草堆值 400 丢失
Haystack 值 500 描述文本 3 在针中存在但已修改 在 newtext3 中,数量 = 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 (last $haystack key) $result["value"] 或 $result["key"] 变为 "null" 因为 $needle 只有 0 和 1 个键! 如何编辑功能? 非常感谢,我不是多维数组专家!

【问题讨论】:

    标签: php arrays multidimensional-array


    【解决方案1】:

    使用新索引 $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
    }
    

    有没有快速的方法?再见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2012-08-28
      • 2019-01-20
      • 1970-01-01
      相关资源
      最近更新 更多