php - How do I get rows to correspond to other rows based on a parent_id , all from the same table -
i assuming not easy way of doing , it's home assignment, bear me please.
i have table in mysql 'menu'
following structure :
id - number parent_id - number (0 root) title - string link - string
the parent_id links id of row , in case product1
products
.
example : 1 | 0 | | about.html 2 | 0 | products | products.html 3 | 2 | product1 | product1.html 4 | 2 | product2 | product2.html 5 | 2 | product3 | product3.html
my goal make set of ul
's :
<ul> <li><a href="about.html"> </a></li> <li><a href="products.html"> products </a> <ul> <li> <a href="product1.html"> product 1 </a></li> <li> <a href="product1.html"> product 1 </a></li> ... </ul> </li> ... </ul>
so far i've made 1 ul
:
<?php function getall() { dbconnect(); $result = mysql_query("select * `menu`"); $listitems = array(); while ($li = mysql_fetch_array($result)) { $listitems[] = $li; } return $listitems; } ?> <ul> <?php include_once 'functions.php'; $listitems = getall(); foreach ($listitems $listitem) { ?> <li><a href="<?php print $listitem['link']; ?>"><?php print $listitem['title']; ?></a></li> <?php } ?> </ul>
this problem starts , can't figure out how make second function or how condition in order "submenu" rows ul
in ul
.
if don´t have huge number of elements in table it´s easy solve this. syed qarib user said, can check if current item has children´s.
the key make paint of html recursive using parent_id.
this code need:
<?php function getelementsbyparentid($parent_id) { dbconnect(); $query = sprintf("select * `menu` parent_id=%s", mysql_real_escape_string($parent_id)); $result = mysql_query($query); <!-- alternative using concat $result = mysql_query("select * `menu` parent_id=".$parent_id); --> $listitems = array(); while ($li = mysql_fetch_array($result)) { $listitems[] = $li; } return $listitems; } function paintchildrens($parent_id) { $listitems = getelementsbyparentid($parent_id); if (count($listitems) > 0) { ?> <ul> <?php foreach($listitems $listitem) { ?> <li><a href="<?php print $listitem['link']; ?>"><?php print $listitem['title']; ?></a></li> <?php paintchildrens($listitem['id']); } ?> </ul> <?php } } include_once 'functions.php'; paintchildrens(null) ?>
i´m not php developer it´s possible code has errors null value check.
Comments
Post a Comment