I have two arrays I want to merge, but leave out elements from the 2nd array that match a value. (id
and otherId
)
I know how to achieve this with a 2nd loop inside a first loop, but I was wondering if this could be achieved using a single loop, or with a specific php function?
This is an example of what I'm doing now:
foreach ($array1 as $item)
{
$id = $item['id'];
foreach ($array2 as $key => $item)
{
if ($item['otherId'] == $id)
{
unset($array2[$key]);
}
}
}
$output = array_merge($array1, $array2);
There will be a lot of elements in both arrays, so I'm looking for the most efficient way of doing this.
Example of arrays:
$array1 = [
[
'id' => 1
'name' => 'item 1'
],
[
'id' => 2
'name' => 'item 2'
],
[
'id' => 3
'name' => 'item 3'
],
[
'id' => 4
'name' => 'item 4'
]
];
$array2 = [
[
'id' => 1,
'otherId' => 2,
'name' => 'item 2'
],
[
'id' => 2,
'otherId' => 3,
'name' => 'item 3'
],
[
'id' => 3,
'otherId' => null,
'name' => 'item 4'
],
[
'id' => 4,
'otherId' => null,
'name' => 'item 5'
]
];
$output = [
[
'id' => 1
'name' => 'item 1'
],
[
'id' => 2
'name' => 'item 2'
],
[
'id' => 3
'name' => 'item 3'
],
[
'id' => 4
'name' => 'item 4'
],
[
'id' => 3,
'otherId' => null,
'name' => 'item 4'
],
[
'id' => 4,
'otherId' => null,
'name' => 'item 5'
]
];