1
Array
(
    [1~course2 20:00] => Array
        (
            [0] => Array
                (
                    [pid] => 30
                    [anz_tn] => 6
                )

            [1] => Array
                (
                    [pid] => 30
                    [anz_tn] => 4
                )

            [2] => Array
                (
                    [pid] => 30
                    [anz_tn] => 5
                )
        )

    [2~Course2 08:30] => Array
        (
            [0] => Array
                (
                    [pid] => 30
                    [anz_tn] => 5
                )

            [1] => Array
                (
                    [pid] => 11
                )

            [2] => Array
                (
                    [anz_tn] => 4
                )
)

....

How can I get the sum of all the "anz_tn" for each subarray? (sum of all [0]['anz_tn'],[1]['anz_tn'], etc..)

I've tried to use $all[][$i]['anz_tn'] but this fails. ($all is the main array, $i is the count of subarrays). Is there a way using array_sum?

Thanks!

2 Answers2

0

please try like this,

$sumArray = array();

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

print_r($sumArray);
US-1234
  • 1,519
  • 4
  • 24
  • 61
  • While this may answer the question it’s always a good idea to put some text in your answer to explain what you're doing. Read [how to write a good answer](http://stackoverflow.com/help/how-to-answer). – Jørgen R Mar 31 '15 at 07:20
0

Thank you, Manadh!

This was pointing me in the right direction. One level of the array was missing (resulting in 'unsupported operand error'), so in the end I came up with this:

$sumArray = array();
foreach ($groupasweek as $s1k=>$s1v) {
    foreach ($s1v as $s2k=>$s2v) {
        foreach ($s2v as $id=>$value) {
            if ($id == 'anz_tn') {
                $sumArray[$s1k][$id] += $value;
            }           
        }
    }
}

Btw, where can I accept an answer?