I have an array of objects which have id and parentId attributes. The id value is unique, but more than one object may have the same parentId value.
If more than one object has the same parentId value, I want to remove all but one (i.e. remove the "siblings").
I thought I could do this easily with nested foreach loops, but it's not working as I expected.
Here's an example:
$objArray = [];
for($i = 0; $i < 2; $i++) {
$obj = new stdClass();
$obj->id = $i;
$obj->parentId = 1;
$objArray[] = $obj;
}
for($i = 2; $i < 4; $i++) {
$obj = new stdClass();
$obj->id = $i;
$obj->parentId = 2;
$objArray[] = $obj;
}
echo 'Before unsetting siblings:<pre>';
print_r($objArray);
echo '</pre>';
// loop over $objArray and remove elements with the same ->parentId (leaving one)
foreach ($objArray as $keyOuter => $objOuter) {
foreach ($objArray as $keyInner => $objInner) {
if ($objInner->id != $objOuter->id // if the inner object is NOT the same as the outer object (i.e. it's a different object)
&& $objInner->parentId == $objOuter->parentId // and if the parent IDs are the same
) {
unset($objArray[$keyInner]); // unset the inner object
}
}
}
echo 'After unsetting siblings:<pre>';
print_r($objArray);
echo '</pre>';
Output:
Before unsetting siblings:
Array
(
[0] => stdClass Object
(
[id] => 0
[parentId] => 1
)
[1] => stdClass Object
(
[id] => 1
[parentId] => 1
)
[2] => stdClass Object
(
[id] => 2
[parentId] => 2
)
[3] => stdClass Object
(
[id] => 3
[parentId] => 2
)
)
After unsetting siblings:
Array
(
)
I expected the first and third objects in the array to remain after the foreach loops, but as you can see all of the objects in the array are deleted.
What am I missing here?
next,current, etc.). I'm even wondering if 2 nested loops should actually work given the explanation.