i am trying to re format a array as tree, main array and child arrays should be grouped by "name" property.
my flat array is like
$flat = [
['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];
i could build tree structure by
$tree = buildTree($flat, 'parent_id', 'id');
function buildTree(array $flatList)
{
$grouped = [];
foreach ($flatList as $node) {
$grouped[$node['parent_id']][] = $node;
}
$fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
foreach ($siblings as $k => $sibling) {
$id = $sibling['id'];
if (isset($grouped[$id])) {
$sibling['children'] = $fnBuilder($grouped[$id]);
}
$siblings[$k] = $sibling;
}
return $siblings;
};
return $fnBuilder($grouped[0]);
}
this works perfectly.
But what i want is build nested array should be grouped by it's "name" property.
so the final output should be like
[
"root1": [{
"id": 1,
"parent_id": 0,
"name": "root1",
"children": [
"ch-1": [{
"id": 3,
"parent_id": 1,
"name": "ch-1",
"children": [
"ch-1-1": [{
"id": 5,
"parent_id": 3,
"name": "ch-1-1"
},
{
"id": 6,
"parent_id": 3,
"name": "ch-1-1"
}
]
]
},
{
"id": 4,
"parent_id": 1,
"name": "ch-1"
}
]
]
},
{
"id": 2,
"parent_id": 0,
"name": "root1"
}
],
"root2": [{
"id": 7,
"parent_id": 0,
"name": "root2",
"children": [
"ch3-1": [{
"id": 9,
"parent_id": 7,
"name": "ch3-1"
},
{
"id": 10,
"parent_id": 7,
"name": "ch3-2"
}
]
]
},
{
"id": 8,
"parent_id": 0,
"name": "root2"
}
]
]
I have been stuck here almost for couple of days. Please help me to solve this problem. Thank you.