我有这个数组:
$a = array(1, 2, 3, 4, 5, 7, 8, 10, 12);
是否有一个函数可以将其转换为:
$b = array(1, 1, 1, 1, 2, 1, 2, 2);
所以基本上:
$b = array ($a[1]-$a[0], $a[2]-$a[1], $a[3]-$a[2], ... ,$a[n]-$a[n-1]);
这是我到目前为止的代码:
$a = $c = array(1, 2, 3, 4, 5, 7, 8, 10, 12);
array_shift($c);
$d = array();
foreach ($a as $key => $value){
$d[$key] = $c[$key]-$value;
}
array_pop($d);
最佳答案
没有内置函数可以为您执行此操作,但您可以将代码转换为函数。此外,您可以使用常规的 for
循环来循环遍历值,而不是创建第二个数组 $c
:
function cumulate($array = array()) {
// re-index the array for guaranteed-success with the for-loop
$array = array_values($array);
$cumulated = array();
$count = count($array);
if ($count == 1) {
// there is only a single element in the array; no need to loop through it
return $array;
} else {
// iterate through each element (starting with the second) and subtract
// the prior-element's value from the current
for ($i = 1; $i < $count; $i++) {
$cumulated[] = $array[$i] - $array[$i - 1];
}
}
return $cumulated;
}
关于php - 累积数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715255/