PHP:同一表和行中的类别和子类别?

PHP:同一表和行中的类别和子类别?,php,mysql,Php,Mysql,我有一张这样的桌子: id di_make di_model 1 Samsung TV656 2 Samsung TV555 3 Sony LCD33 我需要从这个表中创建一个类别和子类别菜单 像这样: 所以我试了一下: $storecategories = ""; $sto

我有一张这样的桌子:

id            di_make              di_model

1             Samsung               TV656  
2             Samsung               TV555
3              Sony                 LCD33  
我需要从这个表中创建一个类别和子类别菜单

像这样:

所以我试了一下:

$storecategories = "";
$storesubcategories = "";

$sql2="SELECT DISTINCT `di_make` FROM `products` ORDER BY id";
$query2 = mysqli_query($db_conx, $sql2);
$existCount2 = mysqli_num_rows($query2);
if ($existCount2!=0) {

while($row2 = mysqli_fetch_array($query2, MYSQLI_ASSOC)){

$di_makeC = $row2["di_make"];


/////Create sub categories/////////
$sql3="SELECT * FROM `products` WHERE di_make='$di_makeC'";
$query3 = mysqli_query($db_conx, $sql3);
$existCount3 = mysqli_num_rows($query3);
if ($existCount3!=0) {

while($row3 = mysqli_fetch_array($query3, MYSQLI_ASSOC)){

$di_modelC = $row3["di_model"];

$storesubcategories .='<li>'.$di_modelC.'</li>';



}
}
/////End of Create sub categories/////////


 $storecategories .= '<li class="dropdown">'.$di_makeC.'
      <ul>
           '.$storesubcategories.'
      </ul>
   </li>';

}
}
$storecategories=”“;
$storesubcategories=“”;
$sql2=“根据id从“产品”订单中选择不同的“生产商”;
$query2=mysqli\u查询($db\u conx,$sql2);
$existCount2=mysqli\u num\u行($query2);
如果($existCount2!=0){
而($row2=mysqli\u fetch\u数组($query2,mysqli\u ASSOC)){
$di_makeC=$row2[“di_make”];
/////创建子类别/////////
$sql3=“从'products'中选择*,其中di_make='$di_make'”;
$query3=mysqli\u查询($db\u conx,$sql3);
$existCount3=mysqli\u num\u行($query3);
如果($existCount3!=0){
而($row3=mysqli_fetch_数组($query3,mysqli_ASSOC)){
$di_modelC=$row3[“di_model”];
$storesubcategories.='
  • “.$di_modelC.
  • ”; } } /////创建子类别结束///////// $storecategories.='
  • '.$di_makeC'
      “.$storesubcategories。”
  • '; } }
    然而,上面的代码行为怪异

    我的意思是,它将创建类别,然后创建子类别,但它将重复第二个类别中的子类别

    像这样:

    有人能就这个问题提出建议吗


    提前感谢。

    不要通过将查询嵌套在循环中来实现这一点(通常应该避免这种情况,因为性能不好)。使用一个查询,首先选择di_make排序的数据,然后实现一个简单的控件中断来创建必要的HTML结构。@CBroe,你有没有可能提供一个控件中断的例子?你可以在查询中尝试
    group by di_make
    。在这里你可以找到一个原则的一般解释:基本上你比较当前“行”与前一行的值,并根据它们是否相同,您决定需要生成什么输出。@shanechiu,group by生成相同的结果!不要通过在循环中嵌套查询来实现这一点(通常情况下,这应该避免,因为性能不好)。使用一个查询,首先选择di_make排序的数据,然后实现一个简单的控件中断来创建必要的HTML结构。@CBroe,你有没有可能提供一个控件中断的例子?你可以在查询中尝试
    group by di_make
    。在这里你可以找到一个原则的一般解释:基本上你比较当前“行”与前一行的值,并根据它们是否相同,您决定需要生成什么输出。@shanechiu,group by生成相同的结果!