php - 使用 PHP 根据星期几从数组中选择数据
问题描述
我有以下代码,取自另一个问题:
<?php
$times = array(
'mon' => '9:00 AM - 12:00 AM',
'tue' => '9:00 AM - 12:00 AM',
'wed' => '9:00 AM - 12:00 AM',
'thu' => '9:00 AM - 12:00 AM',
'fri' => '9:00 AM - 1:00 AM',
'sat' => '9:00 AM - 1:00 PM, 2:00 PM - 1:00 AM',
'sun' => 'closed'
);
function compileHours($times, $timestamp) {
$times = $times[strtolower(date('D',$timestamp))];
if(!strpos($times, '-')) return array();
$hours = explode(",", $times);
$hours = array_map('explode', array_pad(array(),count($hours),'-'), $hours);
$hours = array_map('array_map', array_pad(array(),count($hours),'strtotime'), $hours, array_pad(array(),count($hours),array_pad(array(),2,$timestamp)));
end($hours);
if ($hours[key($hours)][0] > $hours[key($hours)][1]) $hours[key($hours)][1] = strtotime('+1 day', $hours[key($hours)][1]);
return $hours;
}
function isOpen($now, $times) {
$open = 0; // time until closing in seconds or 0 if closed
// merge opening hours of today and the day before
$hours = array_merge(compileHours($times, strtotime('yesterday',$now)),compileHours($times, $now));
foreach ($hours as $h) {
if ($now >= $h[0] and $now < $h[1]) {
$open = $h[1] - $now;
return $open;
}
}
return $open;
}
$now = strtotime('7:59pm');
$open = isOpen($now, $times);
if ($open == 0) {
echo "Is closed";
} else {
echo "Is open. Will close in ".ceil($open/60)." minutes";
}
?>
它按原样工作,但我希望能够输出当天的日程安排,例如:
The schedule for today (thu) is 9:00 AM - 12:00 AM
我怎样才能做到这一点?我知道date('D')
输出当天(星期四),但我无法从数组中提取所需的数据。
解决方案
根据您的问题,最简单的解决方案如下,其余功能您可以使用,或者您可以根据您的逻辑使用。
<?php
$times = array(
'mon' => '9:00 AM - 12:00 AM',
'tue' => '9:00 AM - 12:00 AM',
'wed' => '9:00 AM - 12:00 AM',
'thu' => '9:00 AM - 12:00 AM',
'fri' => '9:00 AM - 1:00 AM',
'sat' => '9:00 AM - 1:00 PM, 2:00 PM - 1:00 AM',
'sun' => 'closed'
);
$data=date("D");
echo "The schedule for today (".strtolower($data).") is ".$times[strtolower($data)];
?>
推荐阅读
- powershell - 为 CSV 文件添加标题
- javascript - 如何在同一个 DOM 控制台中访问嵌套的文档对象?
- node.js - 删除推文中的 URL 卡片 (API)
- java - 只有一些 URL 没有在 Webview 中加载
- mysql - mysql - 如果不存在则插入
- angular7 - Angular:如何访问 ng-template 中的引用变量
- reactjs - 使用 Jest 测试反应组件中的功能
- react-native-navigation - React Native Navigation 在底部选项卡单击时转到堆栈顶部
- bash - Bash:chmod +x localizable.sh:权限被拒绝
- reactjs - Mapbox 地理编码器上的 CSS