$base_arr = Array
(
1 => Array
(
0 => 1,
1 => 2,
2 => 5,
3 => 5
),
3 => Array
(
0 => 1,
1 => 2
),
7 => Array
(
0 => 1,
1 => 4
)
);
我想重新组织元素的顺序并将子数组的总数推送到主数组。我想要返回的结果如下:
$new_arr = Array(
0 => 1,
1 => 2,
2 => 5,
3 => 5,
4 =>13, //this is the total 1+2+5+5 = 13
5 => 1,
6 => 2,
7 => 3,//this is the total 1+2 = 3
8 => 1,
9 => 4,
10 =>5 //this is the total 1+4 = 5
);
谁能帮助我,谢谢。
答案 0 :(得分:3)
这可以为您提供所需的结果:
$new_arr = array();
foreach($base_arr as $base)
{
$count = 0; //Reset in begin of the loop (with 0)
foreach($base as $child)
{
$count += $child; //Count the values
$new_arr[] = $child;
}
$new_arr[] = $count; //Put totale in the array
}
print_r($new_arr);
答案 1 :(得分:2)
在PHP 5.3中尝试闭包的好机会:
$new = array();
array_walk($base_arr, function ($item) use (&$new) {
$new = array_merge($new, $item);
$new []= array_sum($item);
}
);
var_dump($new);
答案 2 :(得分:1)
使用数组函数:
$new=array();
foreach ($base_arr as $bb) {
$new=array_merge($new, $bb);
array_push($new, array_sum($bb));
}