Matt Maclennan
Matt Maclennan

Reputation: 1304

Sub Categories on drop-down menu populated by MySQL

I am new to creating menus via MySQL, and need a tree structure. However, it is not working, as shown on http://www.mattmaclennan.co.uk/a2

What I need to do is group the model numbers into each category, can't figure out how to do it though. Here is my PHP code:

<?
$output = mysql_query("SELECT * FROM bikes, bikeTypes WHERE bikes.model_id = bikeTypes.model_id");
echo "<ul>";
while($row = mysql_fetch_array($output))
{
echo "<li>" . $row['model'];
echo "<ul>";
echo "<li>" . $row['bikeName'] . "</li>";
echo "</ul>";
echo "</li>";
}
echo "<ul>";
?>

I have a table with the Category in (e.g. Adventure, 125CC etc) and a table for the model numbers. It is finding the data fine, it's just organising it in the right structure which is confusing. Any ideas guys?

Thanks!

Upvotes: 0

Views: 665

Answers (1)

air4x
air4x

Reputation: 5683

Try

$result = array();
while($row = mysql_fetch_array($output))
{
  $result[$row['your_category_field_name']][] = $row;
}

foreach ($result as $category => $values) {
  echo '<h4>'.$category.'</h4><ul>';
  foreach ($values as $value) {
    echo "<li>" . $value['model'];
    echo "<li>" . $value['bikeName'] . "</li>";
  }
  echo '</ul>';    

}

Upvotes: 1

Related Questions