Thursday, 30 August 2018

How to get the sum of the values ​​in the specific index of the 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['qty'];
}, $items)
);

$sumvalue = array();

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

 print_r($sumvalue );

0 comments:

Post a Comment