How to merge and overwrite multidimensional array with same key and value with array_merge_recursive ? Supposed I Have two array like below:
$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'),
);
I want to merge and overwrite it with new value (the rule is comparison key with the same value it not overwrite), the expected result is
$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'),
);
With array_merge_recursive it appended not overwrited, I try with array_replace_recursive like below:
$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'),
),
);
It works, but my code look nasty and dirty. Any better solution than mine
Here is a function that would work as you described:
If passed
$arr1and$arr2as defined in the question, the above function will return an array:Of course, if you were to always and only use
prop_idas the unique element then the function could be quite a bit simpler:The only difference in the returned array in this later function is that the keys of the element arrays will be the standard numerical values instead of matching the
prop_ids