3v4l.org

run code in 300+ PHP versions simultaneously
<?php $json = '[ { "id": "X", "label": "X", "data": { "23": 1, "26": 2, "20": 38944000 }, "children": [ { "id": "Y", "label": "Y", "data": { "23": 303000, "26": 704000, "20": 2486000 }, "children": [ { "id": "Z", "label": "Z", "data": { "23": 0, "26": 0, "20": 2486000 }, "children": [], "level": 2, "type": "category" }, { "id": "A", "label": "A", "data": { "23": 303000, "26": 704000, "20": 0 }, "children": [], "level": 2, "type": "category" } ], "level": 1, "type": "company" }, { "id": "B", "label": "B", "data": { "23": 9627000, "26": 9580000, "20": 9428000 }, "children": [ { "id": "C", "label": "C", "data": { "23": 6021000, "26": 6030000, "20": 9428000 }, "children": [], "level": 2, "type": "category" }, { "id": "D", "label": "D", "data": { "23": 2205000, "26": 1932000, "20": 0 }, "children": [], "level": 2, "type": "category" }, { "id": "E", "label": "E", "data": { "23": 737000, "26": 874000, "20": 0 }, "children": [], "level": 2, "type": "category" }, { "id": "F", "label": "F", "data": { "23": 664000, "26": 744000, "20": 0 }, "children": [], "level": 2, "type": "category" } ], "level": 1, "type": "company" } ], "level": 0, "type": "client" } ]'; function flatten($children) { $result = []; foreach($children as $child) { if (count($child->children) == 0) { $result[] = [ $child->type => $child->id, "23" => $child->data->{23}, "26" => $child->data->{26}, "20" => $child->data->{20}, ]; } else { foreach(flatten($child->children) as $deeper) { $result[] = [$child->type => $child->id] + $deeper; } } } return $result; } $tree = json_decode($json); $result = flatten($tree); print_r($result);
Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.26, 8.1.0 - 8.1.13, 8.2rc3
Array ( [0] => Array ( [client] => X [company] => Y [category] => Z [23] => 0 [26] => 0 [20] => 2486000 ) [1] => Array ( [client] => X [company] => Y [category] => A [23] => 303000 [26] => 704000 [20] => 0 ) [2] => Array ( [client] => X [company] => B [category] => C [23] => 6021000 [26] => 6030000 [20] => 9428000 ) [3] => Array ( [client] => X [company] => B [category] => D [23] => 2205000 [26] => 1932000 [20] => 0 ) [4] => Array ( [client] => X [company] => B [category] => E [23] => 737000 [26] => 874000 [20] => 0 ) [5] => Array ( [client] => X [company] => B [category] => F [23] => 664000 [26] => 744000 [20] => 0 ) )

preferences:
74.57 ms | 413 KiB | 5 Q