通过阵列比较今天的名字和时间?

时间:2012-09-24 16:44:25

标签: php arrays codeigniter multidimensional-array

我有一个这样的数组:

阵 (

[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点,它是星期二。然后我想得到Object [0]。但如果是11点钟,我需要得到星期二14:00开始的对象[2]。 它是星期二和16:00然后我需要对象[3]。

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

我尝试使用key =>价值,但我混淆了。 我如何比较日期和时间,如果有关于该组合的课程,只需继续检查即可。

问候 littleblue

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

您可以混合使用DateTime和简单的最小搜索:

$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