【问题标题】:Return arrays from foreach and sum their values从 foreach 返回数组并将它们的值相加
【发布时间】:2013-08-24 14:19:18
【问题描述】:

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

我在 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
)

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

【问题讨论】:

  • 你有没有尝试过或只是想从做你的工作?
  • 您可能会发现 array_reduce 在这里很有帮助

标签: php arrays foreach sum


【解决方案1】:

看看这段代码 sn-p [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-11-24
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多