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);
Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.28, 8.4.1 - 8.4.14, 8.5.0 - 8.5.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) { } } } } } } } }
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.

preferences:
66.53 ms | 409 KiB | 5 Q