0

我有一个这样的数组:

大批 (

[0] => stdClass Object
    (
        [Start] => 08:00
        [dayName] => Tuesday
        [dayID] => 2
        [courseName] => Math

    )

[1] => stdClass Object
    (
        [Start] => 10:00
        [dayName] => Tuesday
        [dayID] => 2
        [courseName] => Geography
    )

[2] => stdClass Object
    (
        [Start] => 14:00
        [dayName] => Tuesday
        [dayID] => 2
        [courseName] => Science
    )

[3] => stdClass Object
    (
        [Start] => 10:00
        [dayName] => Thursday
        [dayID] => 4
        [courseName] => Math
    )

[4] => stdClass Object
    (
        [Start] => 18:00
        [dayName] => Friday
        [dayID] => 5
        [courseName] => History
    )

) 我想做的是,我想将现在的日期和时间与数组中的值进行比较。例如,假设现在是早上 7:00,现在是星期二。然后我想得到对象[0]。但如果是 11:00 点,那么我需要获取周二 14:00 开始的 Object[2]。现在是星期二和 16:00 点,那么我需要 Object[3] 。

如果是周末,那么我需要每周的开始时间,即周二 08:00 的数学课程。

我试图使用 key => value 来获得它,但我搞混了。我如何比较日期和时间,如果有关于该组合的课程,如果不继续检查,只需选择它。

关于小蓝

4

2 回答 2

1
function getObject($array){
    $timeNow = date('U'); // time now
    $oneHour = $timeNow+3600; // time now + 1 hour

    foreach($array as $num => $one){ // loop in each $array
        $date = strtotime($one->Start); // convert start time to timestamp
        if($date >= $timeNow && $date < $oneHour && date('l', $date) == $one->dayName){ // if all criteria met
            return $array[$num]; // return that object
        }
    }
    return array('no data'); // if no criteria is met return no data.
}


$course = getObject($yourArray);
echo $course->courseName;
于 2012-09-24T16:54:22.923 回答
0

您可以混合使用 DateTime 和简单的 min search :

$myCourse = null;//initialisation
$myCourseDate =null;
$now = new DateTime;
foreach($array as $course){
   //get the date from the datas
   $date = DateTime::createFromFormat('l h:i',$course->dayName.' '.course->start);
   if($now < $date && ($myCourseDate === null || $myCourseDate > $date)){
      $myCourse = $course;
      $myCourseDate = $date;
   }
}
//at the end of the loop, you've got the expected course
于 2012-09-24T16:53:36.197 回答