如何从数组中按日期减去值

How to substract values by date from array

我有以下数组,我需要为每个间隔计算值的差异

Array
(
    [0] => Array
        (
            [Mark] => 0
            [ID] => 6236
            [Date] => 2015-03-16 12:04:21
            [Value] => 2
           )
    [1] => Array
        (
            [Mark] => 0
            [ID] => 6236
            [Date] => 2015-04-16 12:04:21
            [Value] => 4
           )
    [2] => Array
        (
            [Mark] => 0
            [ID] => 6236
            [Date] => 2015-05-16 12:04:21
            [Value] => 9
           )
    [3] => Array
        (
            [Mark] => 0
            [ID] => 6236
            [Date] => 2015-06-16 12:04:21
            [Value] => 15
           )
   )

而且我需要为每个间隔做出不同。 像

[Date] => 2015-04-16 12:04:21 => [Value][1] - [Value][0] = 2
[Date] => 2015-05-16 12:04:21 => [Value][2] - [Value][1] = 5
[Date] => 2015-06-16 12:04:21 => [Value][3] - [Value][2] = 6

我该怎么做?

您需要遍历此数组以创建具有这些差异的新数组,例如:

function get_differences($array){
    $new = array();
    foreach($array as $k=>$a){
        if(isset($array[$k-1])){
            $new[$a['Date']] = $a['Value']-$array[$k-1]['Value'];
        }
    }
    return $new;
}

为确保您的日期与键的顺序相同,请先使用 usort 函数按日期排序:

function sortdate($a, $b) {
    return strtotime($a['Date']) - strtotime($b['Date']);
}
usort($array, 'sortdate');

$new = get_differences($array);
echo "<pre>";
print_r($new);
echo "</pre>";

输出:

Array
(
    [2015-04-16 12:04:21] => 2
    [2015-05-16 12:04:21] => 5
    [2015-06-16 12:04:21] => 6
)

如果你的数组 = $temp

你可以这样做

$temp_2 = array();
$result = array();

foreach($temp as $k => $arr){

    if(!count($temp_2)){

        $temp_2 = $arr;

        continue;

    }
    $t = array();
    $t[Date] = $arr[Date];
    $t[Value] = $arr[Value] - $temp_2[Value];
    $result[] = $t;
}
Created new array and it will give you all intervals.
    <?php
    $arr = array(
        array(
            'Mark' => 0,
            'ID' => 6236,
            'Date' => '2015-03-16 12:04:21',
            'Value' => '2'
        ),
        array(
            'Mark' => 0,
            'ID' => 6236,
            'Date' => '2015-04-16 12:04:21',
            'Value' => '4'
        ),
        array(
            'Mark' => 0,
            'ID' => 6236,
            'Date' => '2015-05-16 12:04:21',
            'Value' => '9'
        ),
        array(
            'Mark' => 0,
            'ID' => 6236,
            'Date' => '2015-06-16 12:04:21',
            'Value' => '15'
        ),

    );

    echo '<pre>';
    print_r($arr);

    $newArr = array();
    $i=0;
    foreach($arr as $eachArr){
        foreach($eachArr as $k => $v){
            $newArr[$i][$k] = $v;
            if($i==0){
                $newArr[$i]['interval'] = 0;
            }else{
                $newArr[$i]['interval'] = $newArr[$i][$k] - $newArr[$i-1][$k];
            }
        }
        $i++;
    }

    echo '<<br>';
    print_r($newArr);