Given the following sample dataset,
[FONT=Courier New]+-----------+---------+
| category | item |
+-----------+---------+
| fruit | apple |
| fruit | apricot |
| fruit | banana |
| fruit | plum |
| vegetable | carrot |
| vegetable | onion |
| vegetable | potato |
| vegetable | spinach |
+-----------+---------+[/FONT]
How would I write the query and php so category is formatted in a single tag, like “<h1>” and the items follow with a different tag, like “<li>” so the result would look like this
fruit
- apple
- apricot
- banana
- plum
vegetable
- carrot
- onion
- potato
- spinach
Thanks in advance!
It’s pretty easy if you build an array with the category as the primary KEY then items in this category as secondary array.
<?php
$list = array(
"fruit" => array("apple","apricot","banana","plum"),
"vegetable" => array("carrot","onion","potato","spinach")
);
$display = "";
foreach($list as $category => $items){
$display .= "<h1>$category</h1>\\r";
if(is_array($items)){
$display .= "<ul>\\r";
foreach($items as $item){
$display .= "<li>$item</li>\\r";
}
$display .= "</ul>\\r";
}
}
?>
<html>
<body>
<?php
if(isset($display)){ echo $display; }
?>
</body>
</html
The $list array can be built like this from query.
<?php
$list = array();
//Your database query and While loop would be here
$cat = "{$row['category']}";
$itm = "{$row['item']}";
$list[$cat][] = $itm;
}
?>
Thank you very much! I will now look for a way to put the query results into the array as you have described.