0

我正在制作日历并想显示数组中的元素(公共假期等)。

$holidays = Array (
    "20130101" => "New Year's Day",
    "20130101" => "School Holiday",
    "20130126" => "Australia Day",
...
);

$today = '20130101';
foreach ($holidays as $key => $val) {
    if ($today == $key) echo $val; else;
}

但它只显示“学校假期”,这是数组中的最后一个元素,但我想同时显示“元旦”和“学校假期”。

关于如何解决这个问题的任何建议?先感谢您。

4

3 回答 3

1

您可以以这种格式为每个条目创建一个数组,因为数组键必须是唯一的:

$holidays = Array (
    "20130101" => array (
                         "New Year's Day",
                         "School Holiday",
                  ),
    "20130126" => array("Australia Day"),
...
);

if (isset($holidays[$today]))
    echo implode(", ", $holidays[$today]);

此外,您不必使用大循环,直接数组访问就足够了。

于 2013-05-04T10:56:37.460 回答
0

数组中不能有两个具有相同键的元素。这个:

$holidays = Array (
    "20130101" => "New Year's Day",
    "20130101" => "School Holiday",
    "20130126" => "Australia Day"
);

评估为

[
    "20130101" => "School Holiday",
    "20130126" => "Australia Day"
]

因此,您在循环中只得到一个结果也就不足为奇了。

考虑这样的事情:

$holidays = Array (
    Array ("date" => "20130101", "name" => "New Year's Day"),
    Array ("date" => "20130101", "name" => "School Holiday"),
    Array ("date" => "20130126", "name" => "Australia Day")
);

$today = '20130101';

foreach ($holidays as $holiday) 
{
    if ($holiday["date"] == $today) 
    {
        echo $holiday["name"] . "\n";
    }
}
于 2013-05-04T10:57:44.623 回答
0

您不能使用 == 运算符比较字符串。试试这个!

$holidays = Array (
    "20130101" => "New Year's Day",
    "20130101" => "School Holiday",
    "20130126" => "Australia Day",
    ...
);

$today = '20130101';
foreach ($holidays as $key => $val) {
     if (strcmp($today,$key) == 0) echo $val; else;
}
于 2013-05-04T11:09:23.590 回答