2016-02-19 77 views
2

我与时间戳数组作为价值的工作,例如:PHP得到最接近时间戳,但低于当前的时间戳

  • 1455874500:19/02/2016 09h35
  • 1455879600:19/02/2016 11h00
  • 1455921300:19/02/2016 22h35

而且我喜欢做的事情就是从我的阵列获得最接近的时间戳,但如果这个时间戳比当前时间戳较高(接近>电流时间戳),获取较低的价值。

下面是一个例子来说明我的观点,它是19/02/2016 10h58,我不想得到1455879600(19/02/2016 11h00),但是1455874500(19/02/2016 09h35)然后,当它19/02/2016 11h00,得到1455879600.

我一直对这个代码:

function find_closest($id, $date_now){ 
    global $cnx; 
    $sql = "select position_history from worksheets WHERE id = $id LIMIT 1"; 

    $stmt = $cnx->prepare($sql); 
    try { 
     $stmt->execute(); 
     $result = $stmt->fetch(PDO::FETCH_OBJ); 
    } 
    catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 

    $pos_lane = unserialize($result->position_history); 

    $i=0; 

    $array = array(); 

    foreach ($pos_lane as $item) { 
     // $exp[2] : timestamp 
     $exp = explode("|", $pos_lane[$i]); 
     $array[$exp[1]] = $exp[2]; 
     $i++; 
    } 

    $mostrecent = "0"; 
    foreach($array as $timestampmove) 
    { 
      if ($timestampmove > $mostrecent && $timestampmove < $date_now) { 
      $mostrecent = $timestampmove; 
      } 
    } 

    $closeto = array_search($mostrecent,$array); 

    return $closeto; 

} 

,其目的是选择最近的时间戳今天之前,但它似乎不工作因为我想...

也许你对我有更好的解决方案?

谢谢!

+1

你的意思是这样[这](http://sandbox.onlinephpfunctions.com/code/5b589787f5723bf20ffb6c28879763425ba75fa1) – roullie

回答

0

你可以尝试以下方法:

foreach ($pos_lane as $item) { 
    // $exp[2] : timestamp 
    $exp = explode("|", $pos_lane[$i]); 
    $array[$exp[1]] = (int) $exp[2]; // <<< cast to int 
    $i++; 
} 

$mostrecent = 0; 
$closeto = null; 
foreach($array as $key => $timestampmove) 
{ 
    if ($timestampmove < $date_now) { // <<< make sure $date_now is a Unix timestamp 
     if ($mostrecent < $timestampmove) { 
      $mostrecent = $timestampmove; 
      $closeto = $key; 
     } 
    } 
} 

return $closeto; 
+0

谢谢你的回复,它似乎工作得很好! – FabriceDouceur

1

为什么不使它更简单,并让原始的sql查询为你工作?

$sql = "select MAX(position_history) from worksheets WHERE id = $id and position_history < now() LIMIT 1"; 
+0

谢谢您的答复,但我忘了说... 我的时间戳,这是在position_history序列化,这就是为什么我做爆炸(“ORIGIN | DESTINATION | TIMESTAMP”)来获得我的时间戳($ exp [2])... :( – FabriceDouceur