我试图定义一个逻辑,它将返回一个媒体站每天的下一个直播时间的值。
数组
$liveshows = [
'mon' => [
['start' => '0600', 'end' => '0900', 'host' => 'Joe'],
['start' => '1300', 'end' => '1500', 'host' => 'Carol'],
['start' => '1500', 'end' => '1600', 'host' => 'Cortez'],
['start' => '1700', 'end' => '2100', 'host' => 'Boy George']
],
];过程
date_default_timezone_set('America/New_York');
$day = strtolower(date('D'));
$current_time = date('Hi');
$html=''; $start=[];
if( $day == 'mon' && !empty( $liveshows['mon'] ) )
{
foreach( $liveshows['mon'] as $showtime ) {
if( $current_time >= $showtime['start'] && $current_time <= $showtime['end'] )
$html .= '<h3>' . $showtime['host'] . ' <span>is on air</span></h3>';
// create an array of start times to use in below 'no live show' notice.
$start[] = $showtime['start'];
}
}
// print it
echo $html;在这一点上都工作得很好。
现在,我希望在air上没有活动主机时显示一个通知,因此我使用了current()、next()和end()来循环$start数组。它工作到一定程度,但是失败了,因为数组count()每天都不一致。
if( empty( $html ) )
{
$nextshow='';
if( $current_time < current($start) ) {
$nextshow = current($start);
}
elseif( $current_time < next($start) ) {
$nextshow = next($start);
}
echo '<h3>No live show is on</h3>';
echo '<p>The next live show is at ' . date('g:iA', strtotime( $nextshow )) . '</p>';
}检索时的输出通知是:
从午夜开始
下一场直播节目是早上6:00
在第一场和下一场表演之间
下一场直播节目是下午1:00
在1600 (4PM)显示结束时间之后,进程失败,输出没有下一个数组的5PM值,只是.
下一个直播节目是
如何正确地扫描数组并与当前时间进行比较,以检查是否打开了一个显示,如果没有,则显示下一个显示的时间行吗?
发布于 2021-02-22 08:54:57
我认为在您的情况下使用current/next非常麻烦。您可以通过跟踪任何显示是否在air $isOnAir = true/false上(在下面的代码中)来大大简化代码,如果没有,只需在不同的条件下重复显示数组。
示例:
<?php
declare(strict_types=1);
date_default_timezone_set('America/New_York');
$day = strtolower(date('D'));
$current_time = date('Hi');
// test
$day = 'mon';
$current_time = '1630';
$liveshows = [
'mon' => [
['start' => '0600', 'end' => '0900', 'host' => 'Joe'],
['start' => '1300', 'end' => '1500', 'host' => 'Carol'],
['start' => '1500', 'end' => '1600', 'host' => 'Cortez'],
['start' => '1700', 'end' => '2100', 'host' => 'Boy George'],
],
];
if ($day === 'mon' && !empty($liveshows['mon'])) {
// assume no show is on air
$isOnAir = false;
foreach ($liveshows['mon'] as $showtime) {
if ($showtime['start'] <= $current_time && $current_time <= $showtime['end']) {
// we have a show on air
$isOnAir = true;
// output
echo '<h3>', $showtime['host'], ' <span>is on air</span></h3>';
// break loop
break;
}
}
// without a show on air (see above)
if (!$isOnAir) {
echo '<h3>No live show is on</h3>';
foreach ($liveshows['mon'] as $showtime) {
// find the first where start > current
if ($current_time < $showtime['start']) {
// output
echo '<p>The next live show is at ', date('g:iA', strtotime($showtime['start'])), '</p>';
// and break loop
break;
}
}
}
}https://stackoverflow.com/questions/66311911
复制相似问题