【发布时间】:2019-09-23 08:50:06
【问题描述】:
给定的“平面”数组包含可能是动态的(或多或少的键/值对)的字段(状态、类型等),例如:
$data = array(
array(
"status" => "new",
"type" => "type1",
"source" => "source1",
"other" => "other1",
"count" => "1",
),
...
目标是通过不同数量的分组字段来“分组”多维/嵌套数组。例如,如果需要按4个字段分组:
$groups = array("status", "type", "source", "other");
如果没有子项,则“数据”键应包含所有“原始”数据,如果有子项,则将字段和值分组,如演示中和此图像中的
结果数据集应该如下:
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
)
我从 (rearrange a php array into a nested hierarchical array) 改编了解决方案,但它非常混乱,而且需要大量的内存和时间。能否针对大型数据集(10000 条及更多“平面”数组记录)进行优化,提高性能并美化代码?
这将用于计算每个组的小计(总和、计数、平均值等)。
Demo
【问题讨论】: