3

我创建了一个包含这些行和值的 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
4

3 回答 3

2

确保在查询中按类别排序。然后只需在循环外部添加一个 $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>";
}
于 2013-09-28T22:17:01.780 回答
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;
于 2013-09-28T22:19:25.480 回答
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>';
于 2013-09-28T22:20:25.627 回答