【问题标题】:Multilevel Unordered List from a Query's Result Table查询结果表中的多级无序列表
【发布时间】:2011-04-27 04:57:27
【问题描述】:

我做了一个查询,我可以使用该查询的所有行来填充一个表。

section_id | section | category_id | category | subcategory_id | subcategory

现在我正在尝试从这个填充的表中创建一个多级无序列表。有可能做到吗?结果应该是这样的:

<ul>
  <li>Section Name
    <ul>
      <li>Category name for above section
        <ul>
          <li>Subcategory name for above category and section</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

感谢您的帮助。

【问题讨论】:

    标签: php mysql arrays multi-level


    【解决方案1】:

    可能是这样的(未经测试):

    $tree = array();
    while ($row = mysql_fetch_assoc($result)) {
        $tree[$row['section_id']]['name'] = $row['section'];
        $tree[$row['section_id']]['categories'][$row['category_id']]['name'] = $row['category'];
        $tree[$row['section_id']]['categories'][$row['category_id']]['subcategories'][$row['subcategory_id']]['name'] = $row['subcategory'];
    }
    
    echo '<ul>';
    foreach ($tree as $sec_id => $section) {
        printf('<li><a href="test.php?sec=%d">%s</a><ul>', $sec_id, $section['name']);
        foreach ($section['categories'] as $cat_id => $category) {
            printf('<li><a href="test.php?sec=%d&cat=%d">%s</a><ul>', $sec_id, $cat_id, $category['name']);
            foreach ($category['subcategories'] as $scat_id => $subcategory) {
                printf('<li><a href="test.php?sec=%d&cat=%d&scat=%d">%s</a></li>', $sec_id, $cat_id, $scat_id, $subcategory['name']);
            }
            echo '</ul></li>';
        }
        echo '</ul></li>';
    }
    echo '</ul>';
    

    【讨论】:

    • 效果很好。谢谢你的帮助。
    • 还有一个问题.. 我们如何在这棵树中分配链接?例如,echo '&lt;li&gt;' . $section['name'] . '&lt;ul&gt;'; 应链接到 test.php?sec='$section_id'。主要格式为 ?sec=$section_id&amp;cat=category_id&amp;scat=$subcategory_id 。谢谢。
    • @yahya。哦,来吧。这真的是基本的 PHP。请参阅我更新的答案,但这应该只需要您 5 分钟就可以自己弄清楚。
    • 谢谢,我想看看有没有比我更简单的方法:/* Add ids to array */ $tree[$row['section_id']]['id'] = $row['section_id']; $tree[$row['section_id']]['categories'][$row['category_id']]['id'] = $row['category_id']; $tree[$row['section_id']]['categories'][$row['category_id']]['subcategories'][$row['subcategory_id']]['id'] = $row['subcategory_id']; 链接:foreach ($category['subcategories'] as $subcategory) { echo '&lt;li&gt;&lt;a href="content.php?sec=' . $section['id'] . '&amp;cat=' . $category['id'] . '&amp;scat=' . $subcategory['id'] . '&amp;getDetail="&gt;' . $subcategory['name'] . '&lt;/a&gt;&lt;/li&gt;';Thankx2
    • 基本一样。只是语法糖不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多