我目前正在编写一个脚本,可以使多维数组具有类别的唯一分配给该类别的产品数量(cat_count)以及类别中产品总数的计数其子女类别。
我有一个多维数组,大致如下所示:
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];
}
现在我要做的是为每个数组项添加一个AN EXTRA键: SumCategoryCount => //持有每个项目的SUM包括其子项的计数。 例如。 “动物园动物”的数量为10(1 + 3 + 1 + 2 + 3)。
我无法理解如何做到这一点 - 非常感谢帮助。
最诚挚的问候,
Denlaucr。