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.