Suppose that whe have some object, derived from these class instances
class A
{
...
private b //list of object of class B
}
class B
{
...
private c //list of object of class C
}
class C
{
...
private id
}
Now, somewhere in my code, I’ve got this situation
function findId(array $idList)
{
[...]
}
Where I have to find (for each element of $idList) if an element is contained into this object “cascade”
First solution
//object initialization
foreach($a->getB() as $b)
{
foreach($b->getC() as $c)
{
foreach($idList as $id)
{
if($id == $c->getId())
{
//do something an break the cycle
}
}
}
}
Second Solution
//object initialization
$idSet = array();
foreach($a->getB() as $b)
{
foreach($b->getC() as $c)
{
$idSet[] = $c->getId();
}
}
$idSet = array_unique($idSet);
foreach($idList as $id)
{
if(array_search($id,$idSet) !== false)
{
[...]
}
}
Which is better? There are some alternative methods for reach my goal?
IMPORTANT
There isn’t better data representation. This because these objects are some database object (doctrine2)
You can actually combine the two approaches…
And if you absolutely can’t optimize in a way you won’t have inner loop, set the values of $idList as keys, and values as
true, and useisset()instead ofin_array(), since it’s the fastest