I have a flat array structure ($rows
) with an array of columns ($groupByCols
) that I want to group the data by:
$groupByCols = ['a', 'b'];
$rows = [
[
'a' => 1,
'b' => 10,
'c' => 100
],
[
'a' => 1,
'b' => 20,
'c' => 200
],
[
'a' => 1,
'b' => 20,
'c' => 300
],
[
'a' => 1,
'b' => 30,
'c' => 400
],
[
'a' => 2,
'b' => 40,
'c' => 500
],
[
'a' => 2,
'b' => 50,
'c' => 600
],
[
'a' => 3,
'b' => 60,
'c' => 700
]
];
By looping through the $rows
variable and referencing each of the $groupByCols
values in order, I want to get the following hierarchical array:
$groupedRows = [
[
[
[
'a' => 1,
'b' => 10,
'c' => 100
]
],
[
[
'a' => 1,
'b' => 20,
'c' => 200
],
[
'a' => 1,
'b' => 20,
'c' => 300
]
],
[
[
'a' => 1,
'b' => 30,
'c' => 400
]
]
],
[
[
[
'a' => 2,
'b' => 40,
'c' => 500
]
],
[
[
'a' => 2,
'b' => 50,
'c' => 600
]
]
],
[
[
[
'a' => 3,
'b' => 60,
'c' => 700
]
]
]
];
I'm 99% sure that I need to use recursion for this, but after trying about 10 different things (none of which worked), I can't figure out how to get what I want.
Normally, I would share code I've written thus far, but after thinking about this for several days and not getting anywhere, I really don't have much to show.
I think I just need some general guidance on how I can (assumingly) recursively use the $groupByCols
and $rows
variables to get the $groupedRows
array. Any assistance would be greatly appreciated.
Also, please note that the data above is very simple for demonstration purposes. The real data can be infinity longer and more complex, and I may have to go down 5-6 levels with the $groupByCols
, depending on the nature of what's required.
Thank you.