[英]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.现在我想得到这个数组中所有“值”的总和 - 在这种情况下它将是 2。
How can I do this in PHP?我怎样才能在 PHP 中做到这一点?
I'd say array_column
fits that description rather nicely, don't you?我会说array_column
适合这种描述,不是吗?
$values = array_column($array, 'value');
var_dump($values);
And the aptly named array_sum
will finish it all off nicely恰当命名的array_sum
将很好地完成这一切
$sum = array_sum($values);
In case you're still on PHP5.4 ( array_column
wasn't introduced until 5.5):如果您仍然使用 PHP5.4(直到 5.5 才引入array_column
):
$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)无论如何,它可能会胜过array_column
+ array_sum
方法(因为它不是调用函数,而是依赖于语言结构)
There is a specific function for this: array_reduce有一个特定的函数: 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. array reduce 获取一个数组,一个要在该数组上使用的函数,第三个参数是您在第一次调用该函数时使用的初始数组。
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.你当然可以只使用一个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:您可以使用array_sum()
和array_map()
的组合来实现这一点,如下所示:
$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:如果您使用的是旧版本的 PHP (< 5.5.0),那么您可以使用以下内容:
$sum = array_sum(
array_map(
function($arr) {
return $arr['value'];
},
$originalArray
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.