function getChildrenOf($ary, $id) { foreach ($ary as $el) { if ($el['id'] == $id) return $el; } return FALSE;
If I'm missing something, iterate over the array, looking for something that matches the id key and the identifier you are looking for (then return it as a result). You can also iteratively search (and give me a second code for this code that will check the parentId key) ...
-
The recursive version, includes elements for children:
function getChildrenFor($ary, $id) { $results = array(); foreach ($ary as $el) { if ($el['parent_id'] == $id) { $results[] = $el; } if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE) { $results = array_merge($results, $children); } } return count($results) > 0 ? $results : FALSE; }
Recursive version excluding child elements
function getChildrenFor($ary, $id) { $results = array(); foreach ($ary as $el) { if ($el['parent_id'] == $id) { $copy = $el; unset($copy['children']); // remove child elements $results[] = $copy; } if (count($el['children']) > 0 && ($children = getChildrenFor($el['children'], $id)) !== FALSE) { $results = array_merge($results, $children); } } return count($results) > 0 ? $results : FALSE; }
source share