创建一个新数组,其中包含第一个数组的值之间的差异

时间:2015-11-10 17:43:26

标签: php arrays

我有一系列值。

$array = [1,3,6,7,9,12];

要获取的新数组是值之间的差异。

在新数组中:

$new_array[0] = 0;
$new_array[1] = $array[1] - $array[0];
....
.....
$new_array[n] = $array[n] - $array[n-1];

基于$ array示例,要获取的新数组是:

$new_array = [0,2,3,1,2,3];

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

$array = [1,3,6,7,9,12];
$new_array = array(0);

if (count($array) > 1) { //Check if array has more than 2 elements
    for($i = 1; $i <= count($array) - 1; $i++) {
        $new_array[$i] = $array[$i] - $array[$i - 1]; //Make the calculation here
    }
}

var_dump($new_array);

结果:

array (size=6)
  0 => int 0
  1 => int 2
  2 => int 3
  3 => int 1
  4 => int 2
  5 => int 3

答案 1 :(得分:0)

$array = [1,3,6,7,9,12];
$new_array = array();

# Proceed if array has more than 1 element
if(sizeof($array) > 1) {
    for ($a = 0; $a < sizeof($array); $a++) {
        # Just a check
        if (isset($array[$a - 1]))
            # (Current position) - (current position - 1) 
            # Because array started at position 1 and not 0
            $new_array[] = $array[$a] - $array[$a - 1];
        else
            # Nothing to compare then set it to 0
            $new_array[] = $array[$a] - $array[$a];
    }
}

print_r($new_array);

结果

Array
(
    [0] => 0
    [1] => 2
    [2] => 3
    [3] => 1
    [4] => 2
    [5] => 3
)