2012-10-03 47 views
2

我有此数组:累积阵列

$a = array(1, 2, 3, 4, 5, 7, 8, 10, 12); 

是否有将其转换为一个函数:

$b = array(1, 1, 1, 1, 2, 1, 2, 2); 

所以basicaly:

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

回答

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; 
} 
+1

你应该插入'$阵列= array_values($阵列);'重新索引阵列,避免由于不一致数组键的任何错误(例如,当一个元素被删除) – karka91

+0

让我解释一下:如果一个数组''array = [0 => 1,1 => 2,3 => 3];'被送入你的函数,它将失败,因为不存在索引' 2'。另外 - 计数变量应该得到'$ count - ;',因为它保存的值大于数组中最大的索引 – karka91

+0

@ karka91我接受;我已经更新了我的答案,在'for'循环中包含了全部支持的重新索引。谢谢你的提示! – newfurniturey

1

我认为PHP已经没有此功能的版本。有很多方法来解决这个问题,但你已经写了答案:

$len = count($a); 
$b = array(); 
for ($i = 0; $i < $len - 1; $i++) { 
    $b[] = $a[$i+1] - $a[$i]; 
}