I have 2 arrays where they have some common id
values, but the keys for these id
keys differ slightly.
$comps = [
[
'c_id' => '123',
'status' => 'active'
],
[
'c_id' => '456',
'status' => 'destroyed'
],
[
'c_id' => '789',
'status' => 'active'
]
];
$rests = [
[
'r_id' => 123,
'extra' => 'some extra info for r_id 123'
],
[
'r_id' => 456,
'extra' => 'some extra info for r_id 456'
]
];
My objective here is to return all entries of the $rests
array that have corresponding entries within the $comps
array that have both matching ID values and a status => active
.
How can one achieve this?
I have seen and used array_uintersect()
in the past, however I can’t seem to get this to work in the desired way.
2
Answers
You can achive this with a nested foreach loop.
Output
Here is the
array_uintersect()
implementation with the two rules.This is a good choice because PHP optimizes the comparisons by using a sorting algorithm under the hood.
Code: (Demo)
With outdated PHP: (Demo)
I don’t think that it’s shameful to pre-filter the
$comps
array. (Demo)If interested in a brute force nested loop approach, then avoid doing useless cycles by conditionally breaking and continuing. I mean, think about it, why bother looping on the rests array if the given comps array can be disqualified early. Furthermore, after you make an id match and push the data into the result array, stop the inner loop. (Demo)