$base_arr = Array
(
1 => Array
(
0 => 1,
1 => 2,
2 => 5,
3 => 5
),
3 => Array
(
0 => 1,
1 => 2
),
7 => Array
(
开发者_Python百科 0 => 1,
1 => 4
)
);
I want to re organize the order of element and push the total of sub-array to the main array.the result I want to return like this:
$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
);
Who can help me please ,thanks.
This should give you the result you want:
$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);
Good chance to try closures in 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);
Using array functions:
$new=array();
foreach ($base_arr as $bb) {
$new=array_merge($new, $bb);
array_push($new, array_sum($bb));
}
精彩评论