简体   繁体   中英

How to get sum of values in specific index of multidimensional array using php?

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.

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

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)

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

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