2012-10-03 45 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]; 
}