I'm currently assigned to task in which I will need to group raw array data. The data is very simple and it has root_id
to determine the parent of the element. The task is to group it dynamically based from DB data.
Now, I already tried constructing draft flowchart but I always end up problematic for nested child. I would kindly ask of your help, how to make this possible in PHP or Laravel in a good performance way.
Below in the left, is the raw data array and the right side is the expected grouped array-object.
$data = [
{
id: 1
root: null
},
{
id: 2
root: null
},
{
id: 3
root: 1
},
{
id: 4
root: 2
},
{
id: 5
root: 3
},
{
id: 6
root: 5
},
];
$expectedGroupResult = [
{
id: 1
root: null
child: [
{
id: 3,
root: 1
child: [
{
id: 5,
root: 3,
child: [
{
id: 6,
root: 5,
child: [],
},
]
},
],
},
]
},
{
id: 2,
root: null,
child: [
{
id: 4,
root: 2,
child: []
},
],
}
];