I'm making a new site and I'm struggling with the menu. Some elements (parent: 0) don't have children and some others do have 1 or 2. I'm trying a new approach to make things shorter, safer and easier but I'm stuck at something. Here's my code:
My problem is that inside the FOR LOOP I do get the amount of sub-menu otems correctly but obviously the 'label' is the same as the parent as that is the ARRAY key already in the loop. The original author of this idea at http://wizardinternetsolutions.com/articles/web-programming/dynamic-multilevel-css-menu-php-mysql fixed it with a $label+1 but I'm not executing the SQL search all over again. What should I do?
UPDATE: Here's the complete code that involves that function:
public function sQuery() {
$sql = "SELECT a.id, a.label, a.link, Deriv1.Count
FROM `menu` a
LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1
ON a.id = Deriv1.parent
WHERE a.parent = :parent";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':parent', $this->_mParent, PDO::PARAM_INT);
if ($stmt->execute()) {
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($menuItem = $stmt->fetch()) {
echo "<li class=\"dropdown\">
";
echo "<a href=\"".$menuItem['link']."\" class=\"dropdown-toggle js-activated\">".$menuItem['label']."</a>
";
if ($menuItem['Count'] > 0) {
echo "<ul class=\"dropdown-menu\">
";}
// THIS IS THE PART THAT DOESN'T GET ME THE CORRECT INFO
for ($i = 1; $i <= $menuItem['Count']; $i++) {
echo "<li><a href=\"".$menuItem['link']."\">".$menuItem['label']."</a></li>
";
}
echo "</ul>
";
}
echo "</li><!-- /.dropdown -->
";
}
}
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
The result should be:
- Home
- Browse Catalog
- ------ Browse per category
- ------ Browse per ID
- About Us
and I'm getting:
- Home
- Browse Catalog
- ------ Browse Catalog
- ------ Browse Catalog
- About Us