2013-08-24 140 views
0

在類別概述中,我需要總結所有子類別中研究的所有項目。從foreach返回數組並將它們的值相加

我有一個foreach()函數中的函數countitemsinsubcat(),它爲每個子類別($ id_cat)返回一個數組'$ value'。

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

    $all_values_found [] = $value; 
} 

所以這是$ all_values_found爲具有2子類別類別:

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

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

在類別列表,我要總結每個子類別的陣列的價值,並獲得了「總'陣列,像這樣:

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

對此有何建議?

+0

你有沒有嘗試過或只是想從事你的工作? –

+0

你可能會發現array_reduce在這裏很有幫助 – Orangepill

回答

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]; 

讓我知道如果你需要進一步澄清!請享用!

+0

@StardogBR讓我知道這是否適合你。 –

相關問題