I have a PHP object (or it could be an array) and I want to iterate through its elements and all of its child elements recursively, and find which element has the most number of children.
This is what I have done.
var $max_element = array();
$this->find_longest_element_recursively($data, 0, array());
public function find_longest_element_recursively($object, $index, $max_array) {
if(!is_array((array) $object) || is_string($object) || is_numeric($object) || is_bool($object)) {
} else {
foreach($object as $key => $element) {
if(sizeof((array) $element) > sizeof((array) $this->max_array)) {
$this->max_array = $element;
}
$this->find_longest_element_recursively($element, $index+1, $max_array);
}
}
}
ok. So this works for me. But I just don't think this is the proper way of doing a recursion. I think I can get rid of that $max_element variable and return the actual max_element object as a result of the recursive function, but unsure of how to keep track of the max_element object during the recursion. Love to hear your thoughts. Thanks in advance.