我目前正在编写一个脚本,该脚本可以使多维数组具有唯一分配给该类别(cat_count)的类别产品数量的计数以及该类别中包括其childreng类别的产品总数。
我有一个多维数组,大致如下所示:
Array
(
[0] => Array
(
[CategoryID] => 4
[CategoryName] => Cars
[ParentID] => 0
[CategoryCount] => 0
[children] => Array
(
)
)
[1] => Array
(
[CategoryID] => 1
[CategoryName] => Zoo Animals
[ParentID] => 0
[CategoryCount] => 1
[children] => Array
(
[0] => Array
(
[CategoryID] => 6
[CategoryName] => Lions
[ParentID] => 1
[CategoryCount] => 3
[children] => Array
(
)
)
[1] => Array
(
[CategoryID] => 2
[CategoryName] => Elephants
[ParentID] => 1
[CategoryCount] => 1
[children] => Array
(
[0] => Array
(
[CategoryID] => 3
[CategoryName] => African Elephants
[ParentID] => 2
[CategoryCount] => 2
[children] => Array
(
)
)
)
)
[2] => Array
(
[CategoryID] => 5
[CategoryName] => Zebra
[ParentID] => 1
[CategoryCount] => 3
[children] => Array
(
)
)
)
)
)
创建此数组的脚本是:
public function build($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children')
{
$m = array();
foreach ($d as $e)
{
isset($m[$e[$pk]]) ?: $m[$e[$pk]] = array();
isset($m[$e[$k]]) ?: $m[$e[$k]] = array();
$m[$e[$pk]][] = array_merge($e, array($c => &$m[$e[$k]]));
}
return $m[$r];
}
现在我要做的是为每个数组项添加一个额外的键: SumCategoryCount => // 保存每个项的总和,包括其子项的计数。例如,“动物园动物”的计数为 10 (1 + 3 + 1 + 2 + 3)。
我不知道如何做到这一点 - 非常感谢帮助。
此致,
登劳克。