I\'m building a simple web app at the moment that I\'ll one day open source. As it stands at the moment, the nav is generated on every page load (which will change to be cached
You can run this query:
SELECT c.id AS cid, c.slug AS cslug, c.name AS cname,
s.id AS sid, s.name AS sname
FROM categories AS c
LEFT JOIN snippets AS s ON s.category = c.id
WHERE c.live=1
ORDER BY c.name, s.name
Then iterate thru the results to create the proper heading like:
// last category ID
$lastcid = 0;
while ($r = $navQuery->fetch_object ()) {
if ($r->cid != $lastcid) {
// new category
// let's close the last open category (if any)
if ($lastcid)
printf ('');
// save current category
$lastcid = $r->cid;
// display category
printf ('- %s', $r->cslug, $r->cname);
// display first snippet
printf ('
- %s
', $r->cslug, $r->sname, $r->sname);
} else {
// category already processed, just display snippet
// display snippet
printf ('- %s', $r->cslug, $r->sname, $r->sname);
}
}
// let's close the last open category (if any)
if ($lastcid)
printf ('
');
Note that I used printf
but you should use your own function instead which wraps around printf, but runs htmlspecialchars
thru the parameters (except the first of course).
Disclaimer: I do not necessarily encourage such use of
s.
This code is just here to show the basic idea of processing hierarchical data got with one query.