Search code examples
phpdynamic-arrays

Sum of subarray values


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!


Solution

  • 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);