You need to create a category tree for output in the directory.

<?php function createTree($data) { $test = array( array('item'=>array('id'=>'3','name'=>'third'), 'children'=>array(array('item'=>array('name'=>'first', 'id'=>1)), array('item'=>array('name'=>'second', 'id'=>2)))), array('item'=>array('id'=>'5','name'=>'fifth'), 'children'=>array(array('item'=>array('name'=>'fourth', 'id'=>4)))) ); return $test; } function printTree($tree) { foreach($tree as $item) { echo $item['item']['name']; if(!empty($item['children'])) printTree($item['children']); } } $data = array( array('id'=>1, 'name'=>'first', 'parent_id'=>3), array('id'=>2, 'name'=>'second', 'parent_id'=>3), array('id'=>3, 'name'=>'third', 'parent_id'=>0), array('id'=>4, 'name'=>'fourth', 'parent_id'=>5), array('id'=>5, 'name'=>'fifth', 'parent_id'=>0) ); $tree = createTree($data); printTree($tree); ?> 

How to implement the createTree function so that it returns the correct array to be processed by the printTree function? In this case, for the input data $ data should return an array corresponding to $ test.

  • 3
    You have a looped tree: P - Visman
  • What have you tried to do to solve the problem? What exactly did not work out? - Dmitriy Simushev
  • Corrected example code. - Sevenflash
  • one
    I answered a similar question yesterday ru.stackoverflow.com/q/456260/177613 and found some more solutions on this site. Use search - tutankhamun

2 answers 2

Solved the problem as follows:

 function createTree($data) { $tree = array(); foreach ($data as $item) { $temp = array(); $temp['item'] = array('id' => $item['id'], 'name' => $item['name']); if (!empty($tree[$item['id']]['children'])) $temp['children'] = $tree[$item['id']]['children']; $tree[$item['parent_id']]['children'][] = $temp; } return $tree[0]['children']; } 

UPD: To use the createTree function, you must use an array sorted in the following way.

 function sortByParentID($a, $b) { if($a['parent_id']==$b['parent_id']) return 0; else if($a['parent_id']>$b['parent_id']) return -1; else return 1; } usort($data, sortByParentID); // createTree($data); 

Tell me, is this a normal approach or are there better ways to solve the problem?

    the last answer for me was not suitable
    a little limit
    there is an $result array

      function sortByParentID($a, $b) { if($a['id_boss']==$b['id_boss']) return 0; else if($a['id_boss']>$b['id_boss']) return 1; else return -1; } usort($result, sortByParentID); 

    Further

      $array = $result; $tree = array(); $sub = array( 0 => &$tree ); foreach ($array as $item) { $id = $item['id']; $parent = $item['id_boss']; $branch = &$sub[$parent]; $branch[$id] = array(); $sub[$id] = &$branch[$id]; } 

    and we all have norms