I have this query:
$query='select id, bg_category from products_categories where
visible="1" and parent="0" group by bg_category order by bg_category ASC';
You can imaging from this point I was looping $num_rows going to the child category and than to its child category.. It was working anyway because the number of categories was bellow 20. But now the categories are over 130 and this way of generating category tree is waste of server resoure.. I am now thinking of changing this and looking for php solution that will execute only 1 query. I found this here: Build a tree from a flat array in PHP but couldn't understand / make it work:
$q = mysql_query("SELECT id, parent_id, name FROM categories");
while ($r = mysql_fetch_row($q)) {
$names[$r[0]] = $r[2];
$children[$r[0]][] = $r[1];
}
function render_select($root=0, $level=-1) {
global $names, $children;
if ($root != 0)
echo '<option>' . strrep(' ', $level) . $names[$root] . '</option>';
foreach ($children[$root] as $child)
render_select($child, $level+1);
}
echo '<select>';
render_select();
echo '</select>';
How is this above supposed to work? What I need to pass with render_select(); ?
Also if this solution works, would it save server resource instead of looping queries? Thank you in advance for your help
EDIT: My database has the following category structure:
#id #bg_category #parent
1 electronics 0
2 Phones 1
3 Smartphones 2
4 normalphones 2
Output like this:
<ul>
<li>electronics
<ul class="sublevel">
<li>Phones
<ul><li>Smartphones</li>
</ul></li></ul></li>
</ul>
and etc.. hope this helps