There is given "flat" array with fields (status, type, etc.) which could be dynamic (more or less key/value pairs), like:
$data = array(
array(
"status" => "new",
"type" => "type1",
"source" => "source1",
"other" => "other1",
"count" => "1",
),
...
Objective is to get multidimensional/nested array "grouped" by different count of grouping fields. For example, if is needed to group by 4 fields:
$groups = array("status", "type", "source", "other");
If no children, then "data" key should have all "raw" data, if have children, then group field and value, like in demo and in this image
Resulting data set should be as follows:
Array
(
[0] => Array
(
[fieldName] => status
[value] => new
[children] => Array
(
[0] => Array
(
[fieldName] => type
[value] => type1
[children] => Array
(
[0] => Array
(
[fieldName] => source
[value] => source1
[children] => Array
(
[0] => Array
(
[fieldName] => other
[value] => other1
[data] => Array
(
[0] => Array
(
[status] => new
[type] => type1
[source] => source1
[other] => other1
[count] => 1
)
I adapted solution from (rearrange a php array into a nested hierarchical array) but it's quite messy and it takes large amount of memory and time. Could it be optimized for large datasets (10000 and more "flat" array records), improved performance and beautified code?
This will be used to calculate each group subtotals (sum, count, averages, etc.).