Home > Software design >  Array sum based on the index from each array in PHP
Array sum based on the index from each array in PHP

Time:05-11

I'm trying to use array_sum() function. But when I have multidimensional array, no idea how to use this function.

For eg:

My array look like this:

$array = array(
        array(array('value' =>1100),array('value' =>1000),array('value' =>3000)),
        array(array('value' =>1200),array('value' =>2000),array('value' =>2000)),
        array(array('value' =>1300),array('value' =>4000),array('value' =>1000)),
    );
$arr = [];
foreach($array as $point){
   $arr[] = array_sum(array_column($array, $point[0]['value']));
}
print_r($arr);

I'm expecting the output like:

[0] => Array
        (
            [0] => Array
                (
                    [value] => 3600
                )

            [1] => Array
                (
                    [value] => 7000
                )

            [2] => Array
                (
                    [value] => 6000
                )

        )

Tested here: https://onecompiler.com/php/3y3mxqky9

CodePudding user response:

You can sum your columns doing like this:

foreach($array as $key => $point){
  $arr[] = array_sum(array_column( array_column($array,$key),'value'));
}
print_r($arr);

CodePudding user response:

You can use

var_dump($point);

inside the for each var_dump is very useful when you are working with arrays and objects... I'm sure you'll find the answer by yourself ;)

CodePudding user response:

Looking at the following line:

$arr[] = array_sum(array_column($array, $point[0]['value']));

You are using array_column() wrong. It needs a string as second param.


Consider using this approach:

foreach($array as $point){
    $values = array_column($point, 'value');
    $arr[] = array_sum($values);
}

This will generate

Array
(
    [0] => 5100
    [1] => 5200
    [2] => 6300
)

Online demo

CodePudding user response:

Since you wish to have the sum vertically and not horizontally, the array_column style you used won't work. You can simply achieve this with 2 nested loops like below:

<?php

$arr = [];
foreach($array as $point){
   foreach($point as $k => $v){
      $arr[$k] = ($arr[$k] ?? 0)   $v['value'];
   }
}
print_r($arr); 

Online Demo

  • Related