2017-10-22 67 views
1

我將數組列表中的時間存儲在數組中。我想搜索時間來查看陣列中的時間是否接近當前時間。當與當前時間比較時搜索數組中的時間

示例:我的當前時間是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

回答

0

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'來設置值? –

相關問題