开发者

Can use Array_sum or loop and make sum?

开发者 https://www.devze.com 2023-02-22 20:34 出处:网络
Have an array array(array(\'a\'=>\'s\',\'add\'=>1), a开发者_StackOverflow社区rray(\'a\'=>\'s1\',\'add\'=>2),

Have an array

array(array('a'=>'s','add'=>1),
      a开发者_StackOverflow社区rray('a'=>'s1','add'=>2),
      array('a'=>'s2','add'=>3)
      ...
      ...
     );

I want to sum of all key add together.so result should be 6

Anyone know how to do this?


$sum = 0;
foreach($yourArray as $element) {
    $sum += $element['add'];
}
echo $sum;


$sum = 0;

foreach($array1 as $array) {
    $sum += $array['add'];
}

echo $sum;  // will echo '6'


Unfortunately, array_sum only works on single-dimensional arrays. Since you're working with an array of associative arrays, you're going to have to approach it differently. If you know your array will have the same form as the one you've linked above, you can simply use something like this:

$total = 0;
foreach( $arrs as $arr )
{
    $total += $arr['add'];
}
echo $total;

Where $arrs is the array you've defined above.


One liner echo array_sum(array_column($a, "add"));

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号