具有相同数组名称的Foreach循环数组

时间:2018-07-13 12:05:27

标签: php foreach

我要这样做的是: 我想根据年/月/日回显信息。

我的代码是:

  $data = array(
    "2018" => array(
        "September" => array(
            "02" => array(
                "Line 1"
            ),
            "02" => array(
                "Line 11"
            ),
            "12" => array(
                "Line 2"
            ),
            "31" => array(
                "Line 3"
            )
        ),
        "December" => array(
            "02" => array(
                "Line 11"
            ),
            "12" => array(
                "Line 22"
            ),
            "31" => array(
                "Line 33"
            ),
            "32" => array(
                "Line 66"
            )
        )
    ),
    "2019" => array(
        "May" => array(
            "05" => array(
                "Line z"
            ),
            "15" => array(
                "Line y"
            ),
            "55" => array(
                "Line x"
            )
        )
    )
);


echo '<pre>';
print_r($data);
echo '</pre>';

foreach ($data as $years => $year) {

    echo $years . "<br>";

    foreach ($year as $months => $month) {

        echo $months . "<br>";


        foreach ($month as $days => $day) {


            foreach ($day as $key => $value) {
                echo $days . " - " . $value . "<br>";
            }
        }
    }
}

如您所见,2018年9月有两个日期为2的数组。 我希望在print_r

时看到这个
2018
September
02 - Line 1
02 - Line 11
12 - Line 2
31 - Line 3

但是我得到了这个

2018
September
02 - Line 11
12 - Line 2
31 - Line 3

如何回显2018年9月2日的两个值?

2 个答案:

答案 0 :(得分:3)

您不能有重复的密钥。您两次定义“ 02”。

解决方案:将“ 9月”定义为:

    "September" => array(
        "02" => array(
            "Line 1",
            "Line 11"
        ),
        "12" => array(
            "Line 2"
        ),
        "31" => array(
            "Line 3"
        )
    ),

答案 1 :(得分:0)

duplicate array name

如果使用重复阵列名称,则最后一个阵列将替换为第一个阵列。