I have an old array like this:
$oldArray = [
[
'id' => 123,
'name' => 'abc',
],
[
'id' => 456,
'name' => 'def',
]
];
I have a new array like this:
$newArray = [
[
'id' => 456,
'name' => 'ghi',
],
[
'id' => 789,
'name' => 'jkl',
],
];
And I want the result like this:
$updatedArray = [
[
'id' => 123,
'name' => 'abc',
],
[
'id' => 456,
'name' => 'ghi',
],
[
'id' => 789,
'name' => 'jkl',
],
];
That should match by id
and get me a resultant array.
I want to use only array functions
to do the trick.
I have used code like the below but that doesn't work:
$mergedVariants = array_merge($newArray, $oldArray);
$updatedArray = array_unique($mergedVariants);
CodePudding user response:
The arrays $newArray and $oldArray are required with the id as the key. array_column does that. Then array_replace_recursive() can be used.
$old = array_column($oldArray,null,'id');
$new = array_column($newArray,null,'id');
$updatedArray = array_values(array_replace_recursive($old, $new));
Without array_values() the result array has the 'id' as key. array_replace() is also sufficient for this case.
try self: 3v4l.org