开发者

Multilevel Unordered List from a Query's Result Table

开发者 https://www.devze.com 2023-03-01 03:06 出处:网络
I made a query which i can populate a table with following theads using all rows of that query. section_id | section | category_id | category | subcategory_id | subcategory

I made a query which i can populate a table with following theads using all rows of that query.

section_id | section | category_id | category | subcategory_id | subcategory

Now I am trying to create a multilevel unordered list from this populated table. Is it possible to do it? Result should like this:

<ul>
  <li>Section Name
    <ul>
      <li>Category name for above section
        <开发者_StackOverflow;ul>
          <li>Subcategory name for above category and section</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

Thank you for any help.


Something like this, perhaps (untested):

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

精彩评论

暂无评论...
验证码 换一张
取 消