我有以下数组,我需要为每个区间
区分值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
我该怎么做?
答案 0 :(得分:0)
您需要遍历此数组以创建具有这些差异的新数组,例如:
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
)
答案 1 :(得分:0)
如果你的数组= $ 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;
}
答案 2 :(得分:0)
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);