首页 > 解决方案 > 带有 DATE COMPARE 条件的 FOREACH (PHP)

问题描述

我有一个 JSON 源,我正在尝试遍历它并显示一些结果(最多 9 个结果),这不是问题

问题是我只想显示与某个日期匹配的结果,其中日期可能是准确的或介于 2 个日期之间。

例如,我只想显示日期2019-11-17在事件的timeFrom timeTo内或timeFromtimeTo等于它的事件。在该示例中,它将是事件 1 和 3

这是源样本

{  
      "title":"event 1",
      "timeFrom":"2019-11-16 19:00:00",
      "timeTo":"2019-11-18 22:00:00",
      "listText":"text of the event",
      "url":"https://url",
      "imageUrl":"https://image.jpg",
      "locations":{  
         "title":"Location name",
         "url":"https://location"
      }
   },
      {  
      "title":"event 2",
      "timeFrom":"2019-11-20 19:00:00",
      "timeTo":"2019-11-20 22:00:00",
      "listText":"text of the event",
      "url":"https://url",
      "imageUrl":"https://image.jpg",
      "locations":{  
         "title":"Location name",
         "url":"https://location"
      }
   },
      {  
      "title":"event 3",
      "timeFrom":"2019-11-17 19:00:00",
      "timeTo":"2019-11-17 22:00:00",
      "listText":"text of the event",
      "url":"https://url",
      "imageUrl":"https://image.jpg",
      "locations":{  
         "title":"Location name",
         "url":"https://location"
      }

这是我目前拥有的 foreach

foreach(array_slice($arr, 0, 9) as $data) {  

            //then I will show the result
        }

所以,我不知道如何在 foreach 中创建这个条件。

标签: phpjsonloopsforeach

解决方案


此函数遍历事件数据,查找开始日期和结束日期围绕给定日期的事件:

function find_events($events, $date) {
    $date = new DateTime($date);
    foreach ($events as $event) {
        $from = (new DateTime($event['timeFrom']))->setTime(0,0,0);
        $to = (new DateTime($event['timeTo']))->setTime(0,0,0);
        if ($date >= $from && $date <= $to) {
            echo "{$event['title']} ({$event['listText']}) from {$event['timeFrom']} to {$event['timeTo']}\n";
        }
    }
}
$events = json_decode($json, true);
find_events($events, '2019-11-17');

输出:

event 1 (text of the event) from 2019-11-16 19:00:00 to 2019-11-18 22:00:00 
event 3 (text of the event) from 2019-11-17 19:00:00 to 2019-11-17 22:00:00

3v4l.org 上的演示


推荐阅读