Hello, Google did not help. Task: climb up the tree of an associative array of any level of nesting to the root element. I successfully solved the inverse problem myself (although some resource participants helped me to get rid of the global variable in recursion in code). Tell me at least how to determine the first ancestor of the element. A simplified example:
array( [1] = array( [id]=>1, [parent_id] = 0 [children] = array( [34] => array( [id] => 34, [parent_id] = 1, [children] = array( [7] => array( [id]=7 ) ) ) ) For example, for id = 7 to build a chain 7 -> 34 -> 1 It seems that on php it is generally impossible to implement ...
UPDATE: Reverse Task - find the tree node:
public static function findNode(&$dataset,$id) { if(isset($dataset[$id])) return $dataset[$id]; foreach ($dataset as $value){ if (isset($value['children'])) { $result=self::findNode($value['children'], $id); if ($result) return $result; } } return false; }
parent_idnot a number, but a reference to the parent element. Thus, you can immediately have the correct structure, which will allow to solve the required task. - ReinRaus