I have two arrays of objects,
They are identical except one has more items,
so they would look like
Array [arrayA]
(
[0] => stdClass Object
(
[id] => 2
[name] => interest 1
[description] => interest one
)
[1] => stdClass Object
(
[id] => 4
[name] => interest 3
[description] => interest three
)
)
Array [arrayB]
(
[0] => stdClass Object
(
[id] => 1
[name] => all
[description] => everything
)
[1] => stdClass Object
(
[id] => 2
[name] => interest 1
[description] => interest one
)
[2] => stdClass Object
(
[id] => 4
[name] => interest 3
[description] => interest three
)
[3] => stdClass Object
(
[id] => 5
[name] => interest 4
[description] => interest four
)
)
Now what I want to do is, loop over arrayB, if the object is found in arrayA (maybe compare the ID?) then set [checked] => true else set [checked] = false on arrayB.
What is the easiest way to do this?
I have thought of doing maybe
foreach($arrayB as &$obj){
$obj->checked = false;
foreach($arrayA as $obja){
if($obja->id == $obj->id){
$obj->checked = true;
break;
}
if($obja->id > $obj->id) //thanks to De3pTh0ught
break;
}
}
But there has to be a more efficient way?
You could add a check to cut useless iterations. If you know that the object IDs in your arrays will always be in increasing order, you could include the condition: if $obja’s ID is greater than $obj’s ID, then
break$arrayA’s foreach loop, because that means that $obj will never find a match.