Search code examples
phparraysmultidimensional-arraysumarray-sum

Sum values of specific column in a 2d array


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 the sum of elements with same index? For example - sum of all elements with index 5 or index 1. Is it possible without hardcoding the column/key value?


Solution

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