如何同时显示数组键和值?



我想为我的网站建立一个动态生成的营业时间列表,以突出显示当天。

第一步,我想通过PHP生成HTML列表。不幸的是,这不起作用。我的代码:

<ul>
<?php
/* Sunday = 0 */
$daynumber_of_week = date('w', strtotime('Sunday'));
/* Define Opening Hours */
$openingHours = array(
"sunday" => array("Closed"),
"monday" => array("Closed"),
"tuesday" => array("8.30 am - 3.00 pm"),
"wednesday" => array("8.30 am - 1.30 pm", "2.00 pm - 7.00 pm"),
"thursday" => array("8.30 am - 0.30 pm", "2.00 pm - 7.00 pm"),
"friday" => array("8.30 am - 0.30 pm", "1.00 pm - 6.00 pm"),
"saturday" => array("8.30 am - 2.00 pm")
);
/* Create Opening Hours */
for ($x = 0; $x < count($openingHours); $x++)
{
echo '<li class="list-unstyled-item d-flex">' . $openingHours[$x] . '<span class="ml-auto">' . $openingHours[$x][0] . '</span></li>';
if (isset($openingHours[$x][1]))
{
echo '<li class="list-unstyled-item d-flex"><span class="ml-auto">' . $openingHours[$x][1] . '</span></li>';
}
}
?>
</ul>

我想在回声行中显示以下内容,但它什么也没显示:

$openingHours[$x] -> e.g. wednesday
$openingHours[$x][0] -> first Value of wednesday e.g. "8.30 am - 1.30 pm"
$openingHours[$x][1] -> second Value of wednesday e.g. "2.00 pm - 7.00 pm"

这变得不必要地复杂。使用扩展的 foreach。

$daynumber_of_week = date('w', strtotime('Sunday'));
/* Define Opening Hours */
$openingHours = array(
"sunday" => array("Closed"),
"monday" => array("Closed"),
"tuesday" => array("8.30 am - 3.00 pm"),
"wednesday" => array("8.30 am - 1.30 pm", "2.00 pm - 7.00 pm"),
"thursday" => array("8.30 am - 0.30 pm", "2.00 pm - 7.00 pm"),
"friday" => array("8.30 am - 0.30 pm", "1.00 pm - 6.00 pm"),
"saturday" => array("8.30 am - 2.00 pm")
);
foreach ($openingHours as $key => $value) {
echo '<li class="list-unstyled-item d-flex">' . $key . '<span class="ml-auto">' . $value[0] . '</span></li>';
if (isset($value[1]))
{
echo '<li class="list-unstyled-item d-flex"><span class="ml-auto">' . $value[1] . '</span></li>';
}
}

注意:在您不知道的实例中,您可以使用[]来声明数组,而不是从 PHP 5.4 开始array()

现场示例

代表

JSFiddle

$openHoursHtml = '<ul>';
foreach($openingHours as $day => $openHoursArr)
{
$openHoursHtml .= "<li><span class='day'>" . $day . "</span>";
$openHoursHtml .= "<span class='hours'>" . implode(",", $openHoursArr) . "</span>";
$openHoursHtml .= '</li>';
}
$openHoursHtml .= '</ul>';
echo $openHoursHtml;

最新更新