Looping and comparing objects
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 arra开发者_开发知识库yA
(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.
This can be done with this horrible hack (in 2 lines!):
$p = print_r($arrayA, true);
foreach($arrayB as &$o) $o->checked =substr_count($p, "[id] => {$o->id}\n") == 1;
After some thought about how inefficient substr_count
could be - think of its internal implementation; it cannot be very efficient - I came up with a slightly different method:
$b = print_r($arrayA, true);
foreach($arrayB as &$o)
$o->checked = strpos($b, "[id] => {$o->id}" . PHP_EOL, 60) !== false;
精彩评论