比较两个多维数组并根据匹配键替换值

时间:2018-10-01 03:12:27

标签: php arrays multidimensional-array

我有2个长度不同的数组:

$array1 = Array
(
    [0] => Array
        (
            ['_id'] => "Group1"
            ['M'] => 0
            ['F'] => 0
        )
    [1] => Array
        (
            ['_id'] => "Group2"
            ['M'] => 0
            ['F'] => 0
        )
    [2] => Array
        (
            ['_id'] => "Group3"
            ['M'] => 0
            ['F'] => 0
        )
    [3] => Array
        (
            ['_id'] => "Group4"
            ['M'] => 0
            ['F'] => 0
        )
)


$array2 = Array
(
    [0] => Array
        (
            ['_id'] => "Group2"
            ['M'] => 180
            ['F'] => 200
        )
    [1] => Array
        (
            ['_id'] => "Group4"
            ['M'] => 360
            ['F'] => 500
        )
)

我想比较数组中的['_id']值和如果它们匹配,我将替换['M']和[ 基于对应的['_id],在数组1中与数组2中的那些

所以我想要的输出是:

$array1 = Array
(
    [0] => Array
        (
            ['_id'] => "Group1"
            ['M'] => 0
            ['F'] => 0
        )
    [1] => Array
        (
            ['_id'] => "Group2"
            ['M'] => 180
            ['F'] => 200
        )
    [2] => Array
        (
            ['_id'] => "Group3"
            ['M'] => 360
            ['F'] => 500
        )
    [3] => Array
        (
            ['_id'] => "Group4"
            ['M'] => 0
            ['F'] => 0
        )
)

这是我的代码,但是我似乎无法用新值替换这些值。这些值仍与以前相同。

foreach ($array1 as $defArr)
{
  foreach ($array2 as $dayArr)
  {
    if($dayArr['_id'] == $defArr['_id'])
    {
      $defArr['M'] = $dayArr['M'];
      $defArr['F'] = $dayArr['F'];
    }
  }
}

2 个答案:

答案 0 :(得分:3)

这可以是一个字符的更改:

foreach ($array1 as $defArr)

转到

foreach ($array1 as &$defArr)
#                   ^

&引用运算符指向foreach循环上下文中的原始子数组,而不是临时变量。

但是,显式使用索引要安全一些:

foreach ($array1 as $i => $defArr) {
    foreach ($array2 as $j => $dayArr) {
        if ($dayArr['_id'] == $defArr['_id']) {
            $array1[$i]['M'] = $array2[$j]['M'];
            $array1[$i]['F'] = $array2[$j]['F'];
        }
    }
}

如果速度很重要或$array2大,则算法的时间复杂度为O(n * m)。我建议对$array2进行散列以进行快速查找,如下所示(O(n)):

$lookup = array_reduce($array2, function ($a, $e) {
    $a[$e['_id']] = $e;
    return $a;
});

foreach ($array1 as $i => $e) {
    if (array_key_exists($e['_id'], $lookup)) {
        $array1[$i]['M'] = $lookup[$e['_id']]['M'];
        $array1[$i]['F'] = $lookup[$e['_id']]['F'];
    }
}

Try it!

答案 1 :(得分:0)

<?php
$array1 = [['_id'=>'abc','M'=>0,'F'=>0],['_id'=>'abcd','M'=>0,'F'=>0],['_id'=>'abcde','M'=>0,'F'=>0]];

$array2 = [['_id'=>'abc','M'=>50,'F'=>300],['_id'=>'abcde','M'=>600,'F'=>700]];

foreach($array2 as $key=> $array2value){
  $searched_in_array_1= array_search($array2value['_id'],array_column($array1,'_id'));
  if(is_numeric($searched_in_array_1)) $array1[$searched_in_array_1] = $array2value;
}

var_dump($array1);
?>

在处理数组时,您希望获得有关php数组函数的帮助。我为此使用了array_columnarray_search函数