3

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
0

3 Answers 3

3

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>";
}
Sign up to request clarification or add additional context in comments.

Comments

0
$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>';

1 Comment

Best of all you combine this with the answer given by gview ... meaning optimize your SQL first.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.