gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:26:33 24 4
gpt4 key购买 nike

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

第一步,我想通过 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>';
}
}

注意:在您不知道的情况下,您可以使用[] 来声明一个数组而不是array() 作为PHP 5.4。

实例

Repl

JSFiddle

关于php - 如何同时显示数组键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50553161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com