3v4l.org

run code in 300+ PHP versions simultaneously
<?php $tree = [ 0 => [ 'name' => 'root', 'data' => 0, 'children' => [ '1' => [ 'name' => 'Auto', 'data' => 0, 'children' => [ '2' => [ 'name' => 'Tyres', 'data' => 0, 'children' => [], ], '3' => [ 'name' => 'Audio', 'data' => 1, 'children' => [], ], ], ], '4' => [ 'name' => 'Dishes', 'data' => 0, 'children' => [ '5' => [ 'name' => 'Forks', 'data' => 0, 'children' => [], ], '6' => [ 'name' => 'Knives', 'data' => 0, 'children' => [ '7' => [ 'name' => 'Stainless steel', 'data' => 0, 'children' => [], ], '8' => [ 'name' => 'Silver', 'data' => 0, 'children' => [], ], ], ], ], ], ] ] ]; #var_dump($tree); function reduceTree($tree) { foreach ($tree['children'] as $key => $value) { if ($value['children']) { $tree['children'][$key] = reduceTree($value); } if (!$tree['data'] && !$tree['children']) { unset($tree['children'][$key]); } } return $tree; } $new = reduceTree($tree[0]); var_dump($new);

preferences:
51.67 ms | 402 KiB | 5 Q