<?php $arr = [ ['id'=>1, 'parent_id'=>0, 'name'=>'aaa'], ['id'=>2, 'parent_id'=>0, 'name'=>'bbb'], ['id'=>3, 'parent_id'=>0, 'name'=>'ccc'], ['id'=>4, 'parent_id'=>2, 'name'=>'ddd'], ['id'=>5, 'parent_id'=>2, 'name'=>'eee'], ['id'=>6, 'parent_id'=>5, 'name'=>'fff'], ['id'=>7, 'parent_id'=>2, 'name'=>'ggg'], ['id'=>8, 'parent_id'=>3, 'name'=>'hhh'], ]; //echo '<select>'.make_tree($arr).'</select>'; //$tree = make_tree($arr); $tree = make_tree($arr); $tree = select($tree); echo '<select>'.$tree.'</select>'; function make_tree($arr, $parent_id=0, $deep = 0){ $deep += 2; $new_arr = array(); foreach($arr as $k=>$v){ if($v['parent_id'] == $parent_id){ //$v->name = str_repeat(' ', $deep) . $v->name; $v['children'] = make_tree($arr, $v['id'], $deep); $new_arr[] = $v; } } return $new_arr; } function select($tree, $deep = 0) { $options = ''; $deep+=2; foreach ($tree as $row) { $row['name'] = str_repeat(' ', $deep) . $row['name']; $options .= "<option>{$row['name']}</option>"; if ($row['children']) { $options .= select($row['children'], $deep); } } return $options; }