$arr = [
['id' => 1, 'sub_id' => null, 'name'=> 'name1'],
['id' => 2, 'sub_id' => 1, 'name'=> 'name2'],
['id' => 3, 'sub_id' => 1, 'name'=> 'name3'],
['id' => 4, 'sub_id' => null, 'name'=> 'name4'],
['id' => 5, 'sub_id' => 2, 'name'=> 'name5'],
['id' => 6, 'sub_id' => 4, 'name'=> 'name6'],
];
/* https://stackoverflow.com/a/28429487 */
function buildTree(array &$elements, $parentId = 0) {
$branch = array();
foreach ($elements as &$element) {
if ($element['sub_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[$element['id']] = $element;
unset($element);
}
}
return $branch;
}
function printTree(array $arr, $level=1) {
foreach ($arr as $k => $v) {
print(str_repeat('-', $level) . $v['name'] ."\n");
if(isset($v['children']) && is_array($v['children'])) {
printTree($v['children'], $level + 1);
}
}
}
printTree(buildTree($arr));