PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php $categories = [ [ 'id' => 1, 'name' => 'Category1', 'parent' => null, 'childs' => [ [ 'id' => 3, 'name' => 'Category3', 'parent' => 1, 'childs' => [ [ 'id' => 5, 'name' => 'Category5', 'parent' => 3, 'childs' => [] ], ] ], [ 'id' => 4, 'name' => 'Category4', 'parent' => 1, 'childs' => [ [ 'id' => 6, 'name' => 'Category6', 'parent' => 4, 'childs' => [ [ 'id' => 7, 'name' => 'Category7', 'parent' => 6, 'childs' => [] ], ] ], ] ], ] ], [ 'id' => 2, 'name' => 'Category2', 'parent' => null, 'childs' => [ [ 'id' => 8, 'name' => 'Category8', 'parent' => 2, 'childs' => [ [ 'id' => 9, 'name' => 'Category9', 'parent' => 8, 'childs' => [] ], ] ], [ 'id' => 10, 'name' => 'Category10', 'parent' => 2, 'childs' => [] ], ] ] ]; function func(array $categories): array { function inner(array $categories): array { $res = []; foreach($categories as $category) { $childs = $category['childs']; unset($category['childs']); $res[] = $category; if (count($childs)) { $res = array_merge($res, inner($childs)); } } return $res; } foreach($categories as &$category) { $category['childs'] = inner($category['childs']); } return $categories; } print_r(func($categories));
Show:  
Copy Clear