PHP如何筛选出日期为今日的天气数组?
嘿,我来帮你搞定这个问题!在PHP里要从给定的天气数组里筛选出今日的数据,其实有几种实用的思路,我给你一步步拆解清楚:
方法一:手动遍历筛选(直观易懂)
这种方法适合刚接触PHP的朋友,逻辑非常清晰——逐个检查每个天气条目,把日期匹配今日的挑出来:
// 假设你的天气数据数组是$weatherData $weatherData = [ ['dt' => 1523728800, 'dt_txt' => '2018-04-14 18:00:00', 'main' => [...], 'weather' => [...]], ['dt' => 1523739600, 'dt_txt' => '2018-04-15 21:00:00', 'main' => [...], 'weather' => [...]], // 其他天气条目... ]; // 获取今日的日期字符串(格式和dt_txt的日期部分一致) $today = date('Y-m-d'); $todayWeather = []; foreach ($weatherData as $item) { // 方法1:直接截取dt_txt的前10位(因为格式是Y-m-d H:i:s) $itemDate = substr($item['dt_txt'], 0, 10); // 方法2:用DateTime类解析(更健壮,不怕格式细微变化) // $itemDateTime = new DateTime($item['dt_txt']); // $itemDate = $itemDateTime->format('Y-m-d'); if ($itemDate === $today) { $todayWeather[] = $item; } } // 现在$todayWeather就是今日的所有天气数据 print_r($todayWeather);
这里更推荐用DateTime类的写法,万一后续dt_txt的格式有调整(比如变成2018/04/14 18:00:00),代码也能正常工作,不用改截取逻辑。
方法二:用array_filter简化代码(简洁高效)
如果想让代码更简洁,可以用PHP的array_filter函数,它会自动遍历数组并筛选符合条件的元素:
$today = date('Y-m-d'); // 用匿名函数作为筛选条件 $todayWeather = array_filter($weatherData, function($item) use ($today) { $itemDate = (new DateTime($item['dt_txt']))->format('Y-m-d'); return $itemDate === $today; }); // 注意:array_filter会保留原数组的键,若需要连续索引可以重置 $todayWeather = array_values($todayWeather); print_r($todayWeather);
use($today)的作用是把外部的$today变量传入匿名函数里,这样函数内部就能访问到今日的日期了。
方法三:用时间戳区间筛选(性能最优)
如果你的天气数据里的dt字段是准确的Unix时间戳,那直接用时间戳区间对比会更高效——不需要解析字符串,直接数字比较:
// 获取今日0点的时间戳 $todayStart = strtotime('today'); // 获取明日0点的时间戳(也就是今日的结束边界) $todayEnd = strtotime('tomorrow'); $todayWeather = array_filter($weatherData, function($item) use ($todayStart, $todayEnd) { // 判断当前条目的时间戳是否在今日区间内 return $item['dt'] >= $todayStart && $item['dt'] < $todayEnd; }); $todayWeather = array_values($todayWeather); print_r($todayWeather);
这种方法的优势是性能更好,尤其是当天气数组非常大的时候,数字对比比字符串解析快很多。
你可以根据自己的实际情况选择合适的方法,三种写法都能达到目标~
内容的提问来源于stack exchange,提问作者Bipa
相关产品推荐
相关产品推荐

