I've created a mysql table that includes these rows & values:
category | item_name
=======================
Dinner | Lobster
Dinner | Pizza
Lunch | Sandwich
Lunch | Soup
Lunch | Salad
-------------------------
I then query the database, the result is placed in an array "$menu_selected". I loop through "$menu_selected" to display the results.
foreach($menu_selected as $m):
echo $category = $m->category . "<br>";
echo $item_name = $m->item_name . "<br><br>";
endforeach;
Output:
Dinner
Lobster
Dinner
Pizza
Lunch
Sandwich
Lunch
Soup
Lunch
Salad
How can I filter the categories in PHP so it doesn't echo each category only the first instance of category? The category row value isn't always going to be "Dinner" or "Lunch", I want to be able to echo the category without comparing it to a constant like if($category =='Dinner'){}. I've spend a week researching and can't figure it out. Anyone's help would be greatly appreciated.
I want the output to look like this:
**Dinner**
Lobster
Pizza
Sandwich
**Lunch**
Sandwich
Soup
Salad
Make sure you order by category on your query. Then simply add a $category variable outside your loop, and if that variable has changed, output your header.
$category = '';
foreach($menu_selected as $m) {
if ($m->category != $category) {
echo "**$m->category** <br>";
$category = $m->category;
}
echo $m->category . "<br>";
echo $m->item_name . "<br><br>";
}
Just use 2 foreach method. First one for category second one for items
foreach($menu_selected as $m1):
echo $category = $m1->category . "<br>";
foreach($menu_selected as $m):
echo $item_name = $m->item_name . "<br><br>";
if ($m->category != $m1->category)
{
break;
}
endforeach;
endforeach;
$cat_item_array = ARRAY();
foreach($menu_selected as $m) {
if (!isset($cat_item_array[$m->category])) {
$cat_item_array[$m->category] = $m->item_name;
echo "found new category: ".$m->category . " (Added item: ".$m->item_name.")<br>";
continue;
}
$cat_item_array[$m->category] = $m->item_name;
echo "Added item ".$m->item_name." to category ".$m->category.".<br><br>";
}
print '<pre>'; var_dump($cat_item_array); print '</pre>';