简体   繁体   中英

PHP: Get all values from an "row" in an array

I would like to know how get the sum of all values in a specific "row" of an array.

I got this array for example:

[0] {array( "date" => "2015-01-01", "value" => 5) }
[1] {array( "date" => "2015-01-02", "value" => -3) }
...

Now I would like to get the sum of all "values" in this array - in this case it would be 2.

How can I do this in PHP?

I'd say array_column fits that description rather nicely, don't you?

$values = array_column($array, 'value');
var_dump($values);

And the aptly named array_sum will finish it all off nicely

$sum = array_sum($values);

In case you're still on PHP5.4 ( array_column wasn't introduced until 5.5):

$sum = 0;
foreach ($array as $sub)
{
    $sum += $sub['value'];
}

will do just fine. It'll probably outperform the array_column + array_sum approach anyway (because it's not calling functions, but relying on language constructs)

There is a specific function for this: array_reduce

<?php
$array = array(array('date'=>'', value=>5),array('date'=>'', value=>-3));

$t = array_reduce($array, function($result, $item){
    $result['value'] = $result['value'] + $item['value']; 
    return $result;
}, array('value'=>0));

array reduce gets an array, a function to use on that array, and the third paramter is the initial array you use on the first call of the function.

I used an array here so you can, if you want, also do something with the date (max or min). You could ofcourse just use an int. Then it looks simpeler:

$t = array_reduce($array, function($result, $item){
    $result = $result + $item['value']; 
    return $result;
}, 0);

You can achieve this with a combination of array_sum() and array_map() like so:

$sum = array_sum(
    array_column(
        $originalArray,
        'value'
    )
);

If you're on an older version of PHP (< 5.5.0), then you could use the following:

$sum = array_sum(
    array_map(
        function($arr) {
            return $arr['value'];
        },
        $originalArray
    )
);

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