I\'d like to merge two arrays with each other:
$filtered = array(1 => \'a\', 3 => \'c\');
$changed = array(2 => \'b*\', 3 => \'c*\');
If your keys are non-numeric (which yours are not, so this is not a solution to your exact question), then you can use this technique:
$filtered = array('a' => 'a', 'c' => 'c');
$changed = array('b' => 'b*', 'c' => 'c*');
$merged = array_slice(array_merge($filtered, $changed), 0, count($filtered));
Result:
Array
(
[a] => a
[c] => c*
)
This works because for non-numeric keys, array_merge
overwrites values for existing keys, and appends the keys in $changed
to the end of the new array. So we can simply discard any keys from the end of the merged array more than the count of the original array.
Since this applies to the same question but with different key types I thought I'd provide it.
If you use this with numeric keys then the result is simply the original array ($filtered
in this case) with re-indexed keys (IE as if you used array_values
).
if you want the second array ($b) to be the pattern that indicates that if there is only the key there, then you could also try this
$new_array = array_intersect_key( $filtered, $changed ) + $changed;
This should do it, if I'm understanding your logic correctly:
array_intersect_key($changed, $filtered) + $filtered
Implementation:
$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');
$expected = array(1 => 'a', 3 => 'c*');
$actual = array_key_merge_deceze($filtered, $changed);
var_dump($expected, $actual);
function array_key_merge_deceze($filtered, $changed) {
$merged = array_intersect_key($changed, $filtered) + $filtered;
ksort($merged);
return $merged;
}
Output:
Expected:
array(2) {
[1]=>
string(1) "a"
[3]=>
string(2) "c*"
}
Actual:
array(2) {
[1]=>
string(1) "a"
[3]=>
string(2) "c*"
}