How to get sum of values in specific index of mult

2019-09-25 07:10发布

I have this this array in my code

Array
(
    [1] => Array
        (
            [1] => 4
            [5] => 7
        )

    [2] => Array
        (
            [1] => 2
            [5] => 5
        )

    [3] => Array
        (
            [1] => 2
            [5] => 5
        )

    [4] => Array
        (
            [1] => 6
            [5] => 9
        )

    [5] => Array
        (
            [1] => 6
            [5] => 8
        )

)
1

How could I get sum element with same index? Forexample - sum of all element with index 5 or index 1. If it possible without hardcode.

3条回答
Juvenile、少年°
2楼-- · 2019-09-25 07:45

You could do the following:

function getSumOfId($array, $id) {
   $sumOfId = 0;

   foreach($array as $arr) {
      $sumOfId += $arr[$id];
   }
   return $sumOfId;
}

This way you'll loop through all your arrays, and get the complete sum of a specific ID.

You can use it like this getSumOfId($yourArray, 5)

查看更多
叼着烟拽天下
3楼-- · 2019-09-25 07:57

You can use array_reduce() to sum target values.

$sum = array_reduce($arr, function($carry, $item){
    $carry += $item[5];
    return $carry;
});
echo $sum;

Check code result in demo

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-09-25 08:08

you can use this code

this is demo code for test

$items = array(
 array(1 => 1, 2 => 'White Shirt', 3 => 2),
 array(1 => 2, 2 => 'Blue Shirt', 3 => 3)
);
echo "<pre>";
print_r($items);

echo array_sum(array_column($items, 3)); // output 5

it will work for php 5.5+
 // PHP 5.5+
 echo array_sum(array_column($array, 'yourindexname')); // 

// PHP 4+
function sumArray($item) {
return $item['yourindex'];
}

echo array_sum(array_map('sumArray', $array));

/ PHP 5.3+
echo array_sum(array_map(
function($item) {
    return $item['yourindex'];
}, $items)
);



$sumvalue = array();

foreach ($array as $k=>$sub_array) {
  foreach ($sub_array as $id=>$value) {
  $sumvalue [$id]+=$value;
}
}

 print_r($sumvalue );
查看更多
登录 后发表回答