0

在类别概述中,我需要总结在所有子类别中研究的所有项目。

我在 foreach() 中有一个函数 countitemsinsubcat(),它为每个子类别 ($id_cat) 返回一个数组“$value”。

foreach ($subcategory as $row) {
    $value =& countitemsinsubcat($id_cat);

    $all_values_found [] = $value; 
}

因此,对于具有 2 个子类别的类别,这些是 $all_values_found:

Array (
   [0] => Array(
     [Istudied] => 0
     [Itotal] => 1
    )

[1] => Array (
    [Istudied] => 1
    [Itotal] => 4
    )
)

在类别概述中,我想对每个子类别的数组值求和,并得到一个“总”数组,如下所示:

Array
(
            [Istudied] => 1
            [Itotal] => 5
)

关于如何做到这一点的任何建议?

4

1 回答 1

0

看看这个代码片段 [PHP]:

//The magic happens here:

function concatit($v, $w)
{
    $v[Istudied] += $w[Istudied];
    $v[Itotal] += $w[Itotal];
    return $v;
}

//Declaring the array.

$a = array (array(
        Istudied => 0,
        Itotal => 1
    ),array (
        Istudied => 1,
        Itotal => 4
    )
);

//Making a call to the 'concatit' function declared above from within array_reduce.

$d = array_reduce($a, "concatit");

//Now $d contains the array as you wanted it.

echo $d[Istudied].' '.$d[Itotal];

如果您需要进一步说明,请告诉我!享受!

于 2013-08-24T15:02:08.413 回答