我有以下数组作为 $main_array .想要对子数组中的所有元素求和,例如 [0]=>6, [1]=>11, [2]=>15.>
I've got the following array as $main_array .Wanted to sum up all the elements in the sub array such as [0]=>6, [1]=>11, [2]=>15.
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 2
[1] => 4
[2] => 5
)
[2] => Array
(
[0] => 8
[1] => 4
[2] => 3
)
)
尝试了以下代码.
foreach ($main_array as $key => $value)
$main_array[$key] = Array('1'=>array_sum($value));
print_r($main_array);
但是我得到的数组结构是,
But the array structure I got was,
Array
(
[0] => Array
(
[1] => 6
)
[1] => Array
(
[1] => 11
)
[2] => Array
(
[1] => 15
)
)
我期待数组结构如下.
Array
(
[0] => 6
[1] => 11
[2] => 15
)
提前致谢!
当你调用 Array 函数时,你明确地创建了一个数组,所以你必须从 Array('1'=>array_sum($value));
When you're calling Array function you're explicitly making an array so you have to remove this from Array('1'=>array_sum($value));
这就是你的代码应该是什么样子
This is how your code should look like
foreach ($main_array as $key => $value)
$main_array[$key] = array_sum($value);
这篇关于子数组中所有元素的总和 - PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 SELECT(MYSQL/PHP) 中加入 2 个表Joining 2 tables in SELECT(MYSQL/PHP)(在 SELECT(MYSQL/PHP) 中加入 2 个表)
如何使<option selected=“selected">由How to make lt;option selected=quot;selectedquot;gt; set by MySQL and PHP?(如何使lt;option selected=“selectedgt;由 MySQL 和 PHP 设置?)
使用 PHP 中的数组自动填充选择框Auto populate a select box using an array in PHP(使用 PHP 中的数组自动填充选择框)
PHP SQL SELECT where like search item with multiple wordsPHP SQL SELECT where like search item with multiple words(PHP SQL SELECT where like search item with multiple words)
json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8json_encode produce JSON_ERROR_UTF8 from MSSQL-SELECT(json_encode 从 MSSQL-SELECT 产生 JSON_ERROR_UTF8)
MySQL ORDER BY rand(),名称 ASCMySQL ORDER BY rand(), name ASC(MySQL ORDER BY rand(),名称 ASC)