如何用元素的总和替换子数组?
How to replace subarrays with the sum of their elements?
Array
(
[Apr] => Array
(
[0] => 67
[1] => 392
[2] => 140
[3] => 250
)
[May] => Array
(
[0] => 67
[1] => 392
[2] => 140
[3] => 250
)
)
我想要一个结果数组来保存这样的总和
Array
(
[Apr] => Array
(
[0] => 849
)
[May] => Array
(
[0] => 849
)
)
@Rakesh Tripathi 只需尝试使用 foreach() 和 array_sum(),如下所示:
<?php
$array = array(
"Apr" => array(
67,
392,
140,
250
),
"May" => array(
67,
392,
140,
250
)
);
foreach ($array as $key => $value) {
$array[$key] = array_sum($value);
}
echo "<pre>";
print_r($array);
这是一个使用 array_map()
和 array_sum()
的简洁的函数式语法:
代码:(Demo)
$array=[
"Apr"=>[67,392,140,250],
"May"=>[67,392,140,250]
];
var_export(array_map('array_sum',$array));
输出:
array (
'Apr' => 849,
'May' => 849,
)
Array
(
[Apr] => Array
(
[0] => 67
[1] => 392
[2] => 140
[3] => 250
)
[May] => Array
(
[0] => 67
[1] => 392
[2] => 140
[3] => 250
)
)
我想要一个结果数组来保存这样的总和
Array
(
[Apr] => Array
(
[0] => 849
)
[May] => Array
(
[0] => 849
)
)
@Rakesh Tripathi 只需尝试使用 foreach() 和 array_sum(),如下所示:
<?php
$array = array(
"Apr" => array(
67,
392,
140,
250
),
"May" => array(
67,
392,
140,
250
)
);
foreach ($array as $key => $value) {
$array[$key] = array_sum($value);
}
echo "<pre>";
print_r($array);
这是一个使用 array_map()
和 array_sum()
的简洁的函数式语法:
代码:(Demo)
$array=[
"Apr"=>[67,392,140,250],
"May"=>[67,392,140,250]
];
var_export(array_map('array_sum',$array));
输出:
array (
'Apr' => 849,
'May' => 849,
)