tags:

views:

591

answers:

3

Hello,

How can I add all the values of the key gozhi? Note that 'gozhi' key is dynamic.

<?php
Array
(
    [0] => Array
        (
            [gozhi] => 2
            [uzorong] => 1
            [ngangla] => 4
            [langthel] => 5
        )

    [1] => Array
        (
            [gozhi] => 5
            [uzorong] => 0
            [ngangla] => 3
            [langthel] => 2
        )

    [2] => Array
        (
            [gozhi] => 3
            [uzorong] => 0
            [ngangla] => 1
            [langthel] => 3
        )
)
?>

Example result:

Array
(
    [gozhi] => 10
    [uzorong] => 1
    [ngangla] => 8
    [langthel] => 10
)

Thanks in advance :)

+3  A: 
$newarr=array();
foreach($arrs as $value)
{
  foreach($value as $key=>$secondValue)
   {
       if(!isset($newarr[$key]))
        {
           $newarr[$key]=0;
        }
       $newarr[$key]+=$secondValue;
   }
}
Ngu Soon Hui
Note that this will give you PHP notices (undefined index) every time you access $newarr[$key] on the right side of your assignment, when such values does not yet exist.
Anti Veeranna
I think I add a check to initialize the $newarr[$key]
Ngu Soon Hui
What? I got voted down? For what reason?
Ngu Soon Hui
+4  A: 
$sumArray = array();

foreach ($myArray as $k=>$subArray) {
  foreach ($subArray as $id=>$value) {
    $sumArray[$id]+=$value;
  }
}

print_r($sumArray);
Chris J
That will throw notices for the first iteration as the keys don’t exist yet.
Gumbo
+4  A: 

Here is a solution similar to the two others:

$acc = array_shift($arr);
foreach ($arr as $val) {
    foreach ($val as $key => $val) {
        $acc[$key] += $val;
    }
}

But this doesn’t need to check if the array keys already exist and doesn’t throw notices neither.

Gumbo