查询结果表中的多级无序列表

时间:2011-04-27 04:57:27

标签: php mysql arrays multi-level

我做了一个查询,我可以使用该查询的所有行来填充表格,其中包含以下内容。

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>

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这样的事情,也许(未经测试):

$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>';