我试图找到两个具有两个日期时间和一组日期时间的指数。我想找到两个日期的索引,其中时间最接近datetime数组中的可用时间。这是我尝试过的:
$label = array();
$price = array();
$linePoints = array();
$ind = 0;
// format example $oT = '2018-05-05 12:05:55'
$checkOpen = strtotime($oT);
$checkClose = strtotime($cT);
while ($run = mysqli_fetch_object($query)){
$p = $run->price;
$l = $run->time;
array_push($price, $p);
array_push($label, $l);
// format example: $l = '2018-05-05 12:05:52'
$check = strtotime($l);
$dif = abs($checkOpen - $check);
if($dif < 10){
array_push($linePoints, $ind);
}
$dif = abs($checkClose - $check);
if($dif < 10){
array_push($linePoints, $ind);
}
$ind = $ind +1;
}
此方法的问题在于,由于时间差以毫秒为单位计算,因此该方法可能带来多个匹配项?最后,我只希望数组$linePoints
中有两个索引。关于如何实现这一点的任何想法?谢谢!
答案 0 :(得分:0)
对于此工作,数据库比PHP快得多。您将获得简单性和性能。
if($run = mysqli_query($con,"SELECT event_id FROM Table ORDER BY ABS( DATEDIFF( time, $checkOpen ) ) LIMIT 1")){
$price1 = $run->price;
$label1 = $run->label
}
if($run = mysqli_query($con,"SELECT event_id FROM Table ORDER BY ABS( DATEDIFF( time, $checkClose ) ) LIMIT 1")){
$price2 = $run->price;
$label2 = $run->label
}
答案 1 :(得分:0)
那么,您在这里。您的代码现已修复。
$label = array();
$price = array();
$linePoints = array();
$ind = 0;
// format example $oT = '2018-05-05 12:05:55'
$checkOpen = strtotime($oT);
$checkClose = strtotime($cT);
while ($run = mysqli_fetch_object($query)){
$p = $run->price;
$l = $run->time;
array_push($price, $p);
array_push($label, $l);
// format example: $l = '2018-05-05 12:05:52'
$check = strtotime($l);
$dif = abs($checkOpen - $check);
if($dif < abs ($checkOpen - $linePoints[0]){
$linePoints[0] = $ind);
}
$dif = abs($checkClose - $check);
if($dif < $checkClose - $linePoints[1]){
$linePoints[1] = $ind;
}
$ind = $ind +1;
}