Is there a php function that returns the sum of a row of an associative array?
是否有一个PHP函数返回一个关联数组的行的总和?
If not should I just use a counter and a foreach loop?
如果不是,我应该只使用计数器和foreach循环?
Appreciate it!
欣赏它!
4 个解决方案
#1
9
array_sum will work for you.
array_sum适合你。
$arr = array(
'key1' => 54.3,
65 => 10
);
$sum = array_sum($arr);
#2
22
To get the sum based on a certain column key, use this:
要根据某个列键获取总和,请使用以下命令:
array_sum(array_column($assoc_array, 'key_name'));
#3
3
According to alex's post, you can use array_column()
only if you're using PHP >= 5.5
!
根据alex的帖子,只有当你使用PHP> = 5.5时才能使用array_column()!
If you can't change the PHP-Version and your PHP-Version is lower than 5.5
, you could also go for:
如果您无法更改PHP版本且PHP版本低于5.5,您还可以选择:
array_sum(array_map(function($element){return $element['key_name'];}, $assoc_array));
this will results the same.
这将产生相同的结果。
#4
2
array_sum
http://php.net/array_sum
array_sum http://php.net/array_sum
It sums an array - regardless of index type.
它对数组求和 - 无论索引类型如何。
#1
9
array_sum will work for you.
array_sum适合你。
$arr = array(
'key1' => 54.3,
65 => 10
);
$sum = array_sum($arr);
#2
22
To get the sum based on a certain column key, use this:
要根据某个列键获取总和,请使用以下命令:
array_sum(array_column($assoc_array, 'key_name'));
#3
3
According to alex's post, you can use array_column()
only if you're using PHP >= 5.5
!
根据alex的帖子,只有当你使用PHP> = 5.5时才能使用array_column()!
If you can't change the PHP-Version and your PHP-Version is lower than 5.5
, you could also go for:
如果您无法更改PHP版本且PHP版本低于5.5,您还可以选择:
array_sum(array_map(function($element){return $element['key_name'];}, $assoc_array));
this will results the same.
这将产生相同的结果。
#4
2
array_sum
http://php.net/array_sum
array_sum http://php.net/array_sum
It sums an array - regardless of index type.
它对数组求和 - 无论索引类型如何。