1

我有一个嵌套数组,并希望将其转换为无序列表:

[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 循环中的查询,但认为这可能效率很低?

4

2 回答 2

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>
于 2013-07-21T18:17:44.450 回答
0

您应该添加第三个循环:

   <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>
于 2013-07-21T18:17:48.550 回答