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

时间:2013-09-28 22:11:27

标签: php mysql arrays sorting filtering

我创建了一个包含这些行的mysql表。值:

   category | item_name
   ======================= 
   Dinner   |  Lobster
   Dinner   |  Pizza
   Lunch    |  Sandwich
   Lunch    |  Soup
   Lunch    |  Salad
  -------------------------

然后我查询数据库,结果放在一个数组“$ menu_selected”中。 我遍历“$ menu_selected”以显示结果。

    foreach($menu_selected as $m):
           echo $category = $m->category . "<br>";
           echo $item_name = $m->item_name . "<br><br>";
    endforeach;

输出:

    Dinner
    Lobster

    Dinner
    Pizza

    Lunch
    Sandwich

    Lunch
    Soup

    Lunch
    Salad

如何在PHP中过滤类别,以便它不会仅回显每个类别的第一个类别?类别行值并不总是“晚餐”或“午餐”,我希望能够回应该类别而不将其与if($ category =='Dinner'){}之类的常量进行比较。我花了一周的时间研究,无法弄明白。任何人的帮助将不胜感激。

我希望输出看起来像这样:

 **Dinner**
 Lobster
 Pizza
 Sandwich

 **Lunch**
 Sandwich
 Soup
 Salad

3 个答案:

答案 0 :(得分:1)

确保您在查询中按类别排序。然后只需在循环外添加$ category变量,如果该变量已更改,则输出标题。

$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>";
}

答案 1 :(得分:0)

只需使用2种foreach方法。第一个用于第二个项目

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;

答案 2 :(得分: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>';