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; } 
  • And what prevents you from recurring in depth to maintain a list of paths? - rjhdby
  • Let's take your search code in depth, you will be shown how to deploy the result. - Bookin
  • @Bookin, updated the question - Deus
  • @rjhdby, recursion deep into is needed for completely different purposes and is in no way connected with the question. At this stage of development, I get an array, I need to output all its ancestors for a given element. - Deus
  • 2
    Of course I do not know. As an option when creating a structure, you can assign parent_id not 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

0