如何显示数组键和值?

时间:2018-05-27 14:28:47

标签: php html

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

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

ES INFO:
nodes: 1,
primary-shards: 30,
replica-shards: 30,
total index size: 90gb,
each shards holding 3gb of data,

SYSTEM INFO:
250 SSD ram 28GB

我想在回显线中显示以下内容,但它没有显示任何内容:

<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>

2 个答案:

答案 0 :(得分:4)

这使得不必要的复杂化。使用扩展的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()

直播示例

Repl

JSFiddle

答案 1 :(得分:2)

$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;