douyi5157 2013-09-28 22:11
浏览 154
已采纳

PHP如果变量只有重复只显示第一个实例?

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
  • 写回答

3条回答 默认 最新

  • dqt83336 2013-09-28 22:17
    关注

    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>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度