如何使用 array_merge_recursive 合并和覆盖具有相同键和值的多维数组?假设我有两个数组,如下所示:
$arr1 = array(
// OVERWRITE
array('prop_id' => 1, 'prop_value' => 'batman'),
array('prop_id' => 2, 'prop_value' => 'ironman'),
// NOT OVERWRITE
array('prop_id' => 5, 'prop_value' => 'wonderwoman'),
);
$arr2 = array(
array('prop_id' => 1, 'prop_value' => 'robin'),
array('prop_id' => 2, 'prop_value' => 'superman'),
array('prop_id' => 4, 'prop_value' => 'catwoman'),
);
我想合并并用新值覆盖它(规则是比较键与它不覆盖的相同值),预期结果是
$result = array_merge_overwrite($arr1, $arr2, array('prop_id') /* Comparison Key */);
$result = array(
array('prop_id' => 1 /* Comparison Key */, 'prop_value' => 'robin' /* Comparison value */),
array('prop_id' => 2, 'prop_value' => 'superman'),
array('prop_id' => 4, 'prop_value' => 'catwoman'),
array('prop_id' => 5, 'prop_value' => 'wonderwoman'),
);
使用 array_merge_recursive 它附加没有被覆盖,我尝试使用 array_replace_recursive,如下所示:
$result = array_replace_recursive(
array(
1 => array('prop_id' => 1, 'prop_value' => 'batman'),
2 => array('prop_id' => 2, 'prop_value' => 'ironman'),
5 => array('prop_id' => 5, 'prop_value' => 'wonderwoman'),
),
array(
1 => array('prop_id' => 1, 'prop_value' => 'robin'),
2 => array('prop_id' => 2, 'prop_value' => 'superman'),
4 => array('prop_id' => 4, 'prop_value' => 'catwoman'),
),
);
它可以工作,但我的代码看起来又脏又脏。任何比我更好的解决方案