我有一些数组的数组,我需要转换为新数组并将所有值与所有先前的值相加.例如(数组长度,键和值总是不同),这就是我所拥有的:
Array ( [0] => 1 [1] => 1 [2] => 5 [3] => 1 [4] => 1 [7] => 1 [8] => 3 [9] => 1 )
这就是我需要的:
Array ( [0] => 1 [1] => 2 [2] => 7 [3] => 8 [4] => 9 [7] => 10 [8] => 13 [9] => 14 )
我尝试了许多不同的方法,但总是坚持某些事情,或者意识到我错了.我有一种感觉,我正在尝试重新发明一个轮子,因为我认为必须有一些简单的功能,但没有找到解决方案的运气.这是我尝试的最后一种方式:
$array = array( "0"=> 1,"1"=> 1,"2"=> 5,"3"=> 1,"4"=> 1,"7"=> 1,"8"=> 3,"9"=> 1 ); $this = current($array); $next = next($array); $end = next(end($array)); $sum = 0; $newArray = array(); foreach ($array as $val){ if($val != $end){ $sum = ($this += $next); array_push($newArray,$sum); } } print_r($newArray);
..不幸的是又错了.我花了很多时间找到方法,不知道我需要去哪里,有人可以把我踢向正确的方向吗?
建议你使用array_slice()& array_sum()
$array = array( "0"=>1,"1"=>1,"2"=>5,"3"=>1,"4"=>1,"7"=>1,"8"=>3,"9"=>1); $keys = array_keys($array); $array = array_values($array); $newArr = array(); foreach ($array as $key=>$val) { $newArr[] = array_sum(array_slice($array,$key+1)); } $newArr = array_combine($keys,$newArr); print '<pre>'; print_r($newArr); print '</pre>';
输出:
Array ( [0] => 1 [1] => 2 [2] => 7 [3] => 8 [4] => 9 [7] => 10 [8] => 13 [9] => 14 )
参考: