I have an object containing nested objects and so on. The level of nesting can be assumed to be infinite.
If the object nests other objects, then the children should be stored in an array property called childElements.
The object I am working with looks like this:
Object
childElements
['object1'] => object
childElements
['object11'] => object
['object2'] => object
I would like to get a reference to the object called object11 using recursion. This is the function I am using. The function resides in a class, so $this is used when calling the recursion:
public function recursiveSearch(array $childElements, $elementName){
foreach ($childElements as $key => $element) {
var_dump($key);
if (isset($element->childElements)){
return $this->recursiveSearch($element->childElements, $elementName);
}else{
if ($key == $elementName){
return $childElements[$elementName];
}
}
}
throw new Exception("$elementName could not be found.");
}
I then call my function like so (assuming that object is called $r):
return $this->recursiveSearch($r->childElements, 'object11');
The problem with my code (when looking at the var dumps is that the function will keep travelling towards the inner most object. But once that is done, it terminates, regardless of whether it has visited any other childElements. I believe the issue is due to return $this->recursiveSearch which forces a return prematurely.
How can I structure my recursive function so that it works properly?
The problem is that your code assumes that if an element has child elements, the element must be in the child elements. You actually need three conditions though:
false(don’t throw an exception, because not finding the element is to be expected on most children)Code: