2017-02-27 7 views
0

今後の予定の日付から、最初の日付を取得したいと考えています。私は自分の仕事を書こうとしましたが、それは仕事を成し遂げませんでした。今後最も近い日付を取得

private static function getClosestDate($date, array $dates, $last) { 
    $interval    = array(); 
    $now     = strtotime(date('Y-m-d')); 

    foreach ($dates as $d) { 
     $dateTime   = strtotime($date); 
     $toTime    = strtotime($d); 

     // Do not parse dates older than today 
     if (strtotime($d) < $now) { continue 1; } 

     // Only do dates in the future 
     if ($toTime < $dateTime) { continue 1; } 
     $interval[]   = abs($dateTime - $toTime); 
    } 

    // If there is no interval, use the latest date 
    if (!count($interval)) { 
     return $last; 
    } 

    asort($interval); 
    $closest    = key($interval); 
    return $dates[$closest]; 
} 

このコードは機能しますが、逆も同様です。最後に日付がない場合は、最後の日付である$ lastパラメーターを使用する必要があります。私は人々が上の夜を予約することができた上で日付の範囲を持っているので

私はこれを知ってほしい理由があります。私は彼らが予約できる夜の量を計算する日数の違いを知りたい。日付の違いを計算するのは簡単ですが、次の予約がいつ表示されるかを知る必要があります。これらは$ datesパラメーターで提供されます。

は、私はそれが固定得るために、私のコードでは何を変更する必要があります(私は日付が$日付パラメータに基づいて、過去にあった時はいつでもforeachのを継続しようとした)、または誰かが私のコードを提供することができますか?

+0

なぜあなたは、参照することにより、 '$のdates'を渡していますか?あなたはそれをあなたの関数のどこにでも変更しないでください。 –

+0

使用した日付を削除しようとしましたが、問題が発生しました。参照を偶然残しました。 –

+0

ちょうど一般的なヒント:日付をテキストとして扱わないので、数学を行うことが非常に難しくなります。 –

答えて

0

私はこの問題を自分で修正しました。日付配列を使用するのではなく、日付を再び検索するために日付のキーとして日付を使用しています。これは正しく動作します。

private static function getClosestDate($date, array $dates, $last) { 
    $interval    = array(); 
    $now     = strtotime(date('Y-m-d')); 

    foreach ($dates as $d) { 
     $dateTime   = strtotime($date); 
     $toTime    = strtotime($d); 

     // Do not parse dates older than today 
     if (strtotime($d) < $now) { continue 1; } 

     // Only do dates in the future 
     if ($toTime < $dateTime) { continue 1; } 
     $interval[$d]  = abs($dateTime - $toTime); 
    } 

    // If there is no interval, use the latest date 
    if (!count($interval)) { 
     return $last; 
    } 

    asort($interval); 
    $closest    = key($interval); 

    return $closest; 
} 
関連する問題