嵌套数组到3级无序列表

时间:2013-07-21 18:13:39

标签: php mysql arrays

我有一个嵌套数组,我希望把它变成一个无序列表:

[2009] => Array
    (
        [Show Name 1] => Array
            (
                [0] => Class 1
                [1] => Class 2
            )

    )

[2008] => Array
    (
        [Show Name 2] => Array
            (
                [0] => Class 1
                [1] => Class 2
            )

    )

然后把它变成:

2009
    Show Name 1
        Class 1
        Class 2
2008
    Show Name 2
        Class 1
        Class 2

到目前为止,我已经部分管理了它,能够显示年份,但之后我得到'数组',显示名称应该是:

2012
    Array
    Array
2009
    Array
2008
    Array

我使用以下内容制作了:

    <ul>
    <?php foreach( $results as $year => $shows ): ?>
    <li><?= $year ?>
      <ul>
        <?php foreach( $shows as $show ): ?>
        <li><?= $show ?></li>
        <?php endforeach; ?>
      </ul>
    </li>
    <?php endforeach; ?>
</ul>

更新

我需要为每个结果获取YEAR_ID,SHOW_ID,CLASS_ID,以便我可以将它们传递给URL。类似的东西:

        <ul class="no-bullet">
        <?php foreach( $results as $year => $shows ): ?>
        <li><h2><?= $year ?></h2>
          <ul class="no-bullet">
            <?php foreach( $shows as $show_name => $show ): ?>
            <li><h4><?= $show_name ?></h4></li>
                 <ul class="no-bullet">
                      <?php foreach( $show as $class ): ?>
                      <li><a href="results.html?year=$yearid&show=$showid&class=$classid"><?= $class ?></a></li>
                      <?php endforeach; ?>
                 </ul>
            <?php endforeach; ?>
          </ul>
        </li>
        <?php endforeach; ?>
    </ul>

然而,我没有最模糊的地方从哪里开始。我在foreach循环中考虑了一个查询,但认为这可能效率很低?

2 个答案:

答案 0 :(得分:1)

您需要将$show视为一个数组,然后只提取您想要的部分,如下所示:

<ul>
    <?php foreach( $results as $year => $shows ): ?>
    <li><?= $year ?>
      <ul>
        <?php foreach( $shows as $show_name => $show ): ?>
        <li><?= $show_name ?>
             <ul>
                  <?php foreach( $show as $class ): ?>
                  <li><?= $class ?></li>
                  <?php endforeach; ?>
             </ul>
        </li>
        <?php endforeach; ?>
      </ul>
    </li>
    <?php endforeach; ?>
</ul>

答案 1 :(得分:0)

你应该添加第3个循环:

   <ul>
    <?php foreach( $results as $year => $shows ): ?>
    <li><?= $year ?>
      <ul>
        <?php foreach( $shows as $showname=>$show_list ): ?>
             <li><ul>
             <?php foreach( $show_list as $show ): ?>
                 <li><?= $show ?></li>
             <?php endforeach; ?>
             </ul>
        <?php endforeach; ?>
      </ul>
    </li>
    <?php endforeach; ?>
</ul>