0

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

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>

感谢您的任何帮助。

4

1 回答 1

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>';
于 2011-04-27T05:28:00.490 回答