3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?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);
based on aWmaC
Output for 5.6.0 - 5.6.30, hhvm-3.12.14 - 3.17.3, 7.0.0 - 7.3.1
array(3) { ["name"]=> string(4) "root" ["data"]=> int(0) ["children"]=> array(2) { [1]=> array(3) { ["name"]=> string(4) "Auto" ["data"]=> int(0) ["children"]=> array(2) { [2]=> array(3) { ["name"]=> string(5) "Tyres" ["data"]=> int(0) ["children"]=> array(0) { } } [3]=> array(3) { ["name"]=> string(5) "Audio" ["data"]=> int(1) ["children"]=> array(0) { } } } } [4]=> array(3) { ["name"]=> string(6) "Dishes" ["data"]=> int(0) ["children"]=> array(2) { [5]=> array(3) { ["name"]=> string(5) "Forks" ["data"]=> int(0) ["children"]=> array(0) { } } [6]=> array(3) { ["name"]=> string(6) "Knives" ["data"]=> int(0) ["children"]=> array(2) { [7]=> array(3) { ["name"]=> string(15) "Stainless steel" ["data"]=> int(0) ["children"]=> array(0) { } } [8]=> array(3) { ["name"]=> string(6) "Silver" ["data"]=> int(0) ["children"]=> array(0) { } } } } } } } }