<?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);
preferences:
53.21 ms | 402 KiB | 5 Q