2

我有这个数组:

$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);
4

2 回答 2

2

没有内置函数可以为您执行此操作,但您可以将代码合二为一。$c此外,您可以使用常规for循环来遍历这些值,而不是创建第二个数组:

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;
}
于 2012-10-03T19:19:28.557 回答
1

我认为 php 没有内置函数。有很多方法可以解决这个问题,但你已经写了答案:

$len = count($a);
$b = array();
for ($i = 0; $i < $len - 1; $i++) {
  $b[] = $a[$i+1] - $a[$i];
}
于 2012-10-03T19:21:55.493 回答