简体   繁体   中英

Looping and sum the array values in PHP

I have an array like this:

array(5) {
         ["Uniform"]=>
      array(2) {
        [0]=>
        array(2) {
          ["invoice_pname"]=>
          string(7) "Uniform"
          ["amount"]=>
          string(3) "900"
        }
        [1]=>
        array(2) {
          ["invoice_pname"]=>
          string(7) "Uniform"
          ["amount"]=>
          string(3) "450"
        }
      }

      ["Tuition Fee"]=>
      array(2) {
        [0]=>
        array(2) {
          ["invoice_pname"]=>
          string(11) "Tuition Fee"
          ["amount"]=>
          string(3) "300"
        }
        [1]=>
        array(2) {
          ["invoice_pname"]=>
          string(11) "Tuition Fee"
          ["amount"]=>
          string(3) "300"
        }
      }
    }

I want to add the array values inside the key elements, like:

Uniform => 1350

Tuition Fee => 600

What I do is I use foreach as the loop,

 $results = array();
 foreach ($result as $key => $resultant) {
    foreach ($resultant as $value) {
          $results[$key][] += $value['amount'];  
     }
  }

  var_dump($results);

but it's showing an error

<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message:  Undefined index: Uniform</p>
<p>Filename: controllers/Home.php</p>
<p>Line Number: 2787</p>
<p>Backtrace:</p>

Can anybody help me? I want to show it in a table.

Looking to your data you should iterate over result['Uniform']

$results = array();
  foreach ($result['Uniform'] as $key => $resultant) {
     foreach ($resultant as $value) {
        $results[$key][] += $value['amount'];  
     }
  }

because seem is this this key the one that contain the valid array for sum

You can use array_column and array_sum .
That way you don't need to loop the full array.

Foreach($arr as $key => $a){
    $res[$key] = array_sum(array_column($a, "amount"));
}
Var_dump($res);

https://3v4l.org/Wba3Q

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM