按日期时间对数组进行分组,并从中选择最大日期时间

时间:2017-09-19 07:44:50

标签: php arrays laravel datetime

我的查询是

   $fuel_histories = FuelHistory::where('device_id',$Device->id)
           ->where('when','<',$to_date)
           ->where('when','>',$from_date)
           ->select('when','value')
           ->orderBy('when','asc')->get();



     $data = [];
     $dates=[];

     foreach($fuel_histories as $key=>$value):
       $data[$value->when->toDateTimeString()]= $value->value;
     endforeach;

我有这样的数组,其中key是dateTime,value是数字

[2017-09-17 19:53:24] => 6
[2017-09-18 11:53:15] => 1.212
[2017-09-18 11:54:25] => 1.212
[2017-09-18 12:07:40] => 1.212
[2017-09-18 12:07:58] => 8
[2017-09-18 12:25:09] => 12
[2017-09-18 12:25:56] => 19
[2017-09-18 12:37:25] => 17
[2017-09-19 19:54:47] => 1
[2017-09-22 19:54:36] => 2

这里我有多个具有不同时间但相同日期的键。 如果某些键具有相同的日期和时间是24小时格式,我需要最新的日期时间。所以具有相同日期的键是

[2017-09-18 11:53:15] => 1.212
[2017-09-18 11:54:25] => 1.212
[2017-09-18 12:07:40] => 1.212
[2017-09-18 12:07:58] => 8
[2017-09-18 12:25:09] => 12
[2017-09-18 12:25:56] => 19
[2017-09-18 12:37:25] => 17

最长时间是

  

12点37分25秒

所以我需要一对

  

[2017-09-18 12:37:25] =&gt; 17

最后我的预期输出是

 [2017-09-17 19:53:24] => 6
 [2017-09-18 12:37:25] => 17
 [2017-09-19 19:54:47] => 1
 [2017-09-22 19:54:36] => 2

2 个答案:

答案 0 :(得分:0)

$arr = [
    '2017-09-17 19:53:24' => 6,
    '2017-09-18 11:53:15' => 1.212,
    '2017-09-18 11:54:25' => 1.212,
    '2017-09-18 12:07:40' => 1.212,
    '2017-09-18 12:07:58' => 8,
    '2017-09-18 12:25:09' => 12,
    '2017-09-18 12:25:56' => 19,
    '2017-09-18 12:37:25' => 17,
    '2017-09-19 19:54:47' => 1,
    '2017-09-22 19:54:36' => 2
];

$dates = [];
$times = [];
$result = [];

foreach ($arr as $key => $val) {
    $dt = explode(' ', $key);
    if (!in_array($dt[0], $dates)) $dates[] = $dt[0];
    if (!isset($times[$dt[0]]) || strtotime($times[$dt[0]]) < strtotime($dt[1])) {
        $times[$dt[0]] = $dt[1];
    }
}

foreach ($dates as $val) {
    $key = "{$val} {$times[$val]}";
    $result[$key] = $arr[$key];
}

print_r($result);

P.S。正如JustBaron所说,你应该在添加配对前更好地检查最新时间。

答案 1 :(得分:0)

试试这个:

$prevDate = "";
$prevTime = "";
$result = [];
foreach($data as $key => $val){
    list($date,$time) = explode(' ', $key);
    if($date == $prevDate){
        $prevTime = $time;
        continue;
    }
    else if($prevDate !== "") {
        array_pop($result);
        $result[$prevDate." ".$prevTime] = $data[$prevDate." ".$prevTime];
    }

    $prevTime = $time;
    $prevDate = $date;
    $result[$key] = $val; 
}

print_r($result);