stand stand - 2 months ago 19
PHP Question

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.

Answer Source

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