当与当前时间比较时搜索数组中的时间

问题描述:

我将数组列表中的时间存储在数组中。我想搜索时间来查看阵列中的时间是否接近当前时间。当与当前时间比较时搜索数组中的时间

示例:我的当前时间是01:16所以在阵列有01.0001:3002:0005:00。如果我的当前时间显示为01:16或更大,则最接近的时间将是01:00,所以我想要得到整数值,它是3。如果我的当前时间显示01:30或大于01:30数组中的时间,则正确的时间将是01:30,因此我想要获得值3。如果我的当前时间显示02:00或大于阵列02:00中的时间,则正确的时间将为02:00,因此我想要获得值405.00 ..等等。

下面是代码:

function get_shows($day,$channel_id, DateTime $dt, $today = false) 
{ 

    $ch = curl_init(); 
    curl_setopt_array($ch, array(
     CURLOPT_USERAGENT => '', 
     CURLOPT_TIMEOUT => 30, 
     CURLOPT_CONNECTTIMEOUT => 30, 
     CURLOPT_HEADER => false, 
     CURLOPT_RETURNTRANSFER => true, 
     CURLOPT_FOLLOWLOCATION => true, 
     CURLOPT_MAXREDIRS => 5, 
     CURLOPT_SSL_VERIFYPEER => false 
    )); 

    $date = $dt->format('Y-m-d'); 
    $tz = $dt->getTimezone(); 

    $now = new DateTime('now', $tz); 
    $today = $now->format('Y-m-d'); 
    $shows = array(); 
    $url = 'https://www.example.com?date=' . $date; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    $body = curl_exec($ch); //get the page contents 
    $channel_row = $row_channels[0][0]; // Woksepp: 0 = First row. 
    $pattern23 = "/<a class=\"prog\" href=\"(.*?)\">.*?<span class=\"time\">(.*?)<\/span>.*?<span class=\"title\" href=\"\#\">(.*?)<\/span>.*?<span class=\"desc\">(.*?)<\/span>/s"; 
    preg_match_all($pattern23, $channel_row, $d); 
    $show_times = $d[2]; 

    if($day==0) 
    { 
     //check if my current time is close to the time in the arrays then set the $flag value 
    //$flag = $i 
    } 
} 
?> 

这是效果

Array ([0] => 23:10 [1] => 00:40 [2] => 01:00 [3] => 01:30 [4] => 02:00 [5] => 05:00 
[6] => 06:00 [7] => 08:00 [8] => 08:30 [9] => 09:00 [10] => 10:00 
[11] => 10:30 [12] => 11:00 [13] => 11:25 [14] => 13:30 [15] => 13:55 
[16] => 16:00 [17] => 16:25 [18] => 16:55 [19] => 19:00 [20] => 19:55 
[21] => 22:15 [22] => 22:30 [23] => 23:30 [24] => 01:30) 

我所希望做的是检查是否在接近当前的时间,因此阵列的时间我想获得整数值来设置$flag的值就像这个$flag = $i

你能告诉我一个例子,我可以如何比较数组中的时间与当前时间,因为它接近,所以我想获得整数值?

+0

“*数组有'01.00','01:30','02:00'和'05:00'。如果我当前时间显示'01:16'或大于,最接近时间将是'01:00'*“ - ”1:30关闭到1:16(相隔14分钟)比1:00是(16分钟)。 – ccKep

PHP有一个漂亮的功能strtotime()它可以让你将一个字符串转换为一个unix时间戳,这使得它更容易比较两次。

然后,你将不得不遍历您的阵列,并找到用最少的差值(当前时间绝对值减去数组中的时间)的时间,并保存在一个变量,特定时间的数组键。

$currentTime = time(); 
$minTimeValue = PHP_INT_MAX; 
$minTimeKey = -1; 

foreach ($array as $key => $time) { 
    $thisTimeDifference = abs($currentTime - strtotime($time)); 
    if ($thisTimeDifference < $minTimeValue) { 
     $minTimeKey = $key; 
     $minTimeValue = $thisTimeDifference; 
    } 
} 
+0

谢谢,那么当我的当前时间等于或大于数组中的时间时,如何使用'$ flag'来设置值? –