嵌套循环但避免重复第一个循环

时间:2017-01-05 17:32:20

标签: php

我有两张桌子;一个是类别,另一个是 sub_category

首先,我想显示 category 中的所有项目并存储每个类别的值,然后显示与该类别相关的所有 sub_categories ,但该类别不应重复(对于所有子类别,它应该只显示一次)。

this is the output

<?php 
    $abcd = $mysqli->query("SELECT * FROM categories;");
    while($obj = $abcd->fetch_object())
    {
        $category = $obj->name;
        $results = $mysqli->query("SELECT * FROM `sub-category` WHERE category = '$category';");
        while($omg=$results->fetch_object())
        {
            echo $category. ' '.$omg->subcategory.'<br>';
        }
        echo $omg->subcategory;
    }
?>

2 个答案:

答案 0 :(得分:1)

创建一个子类数组并将它们内部删除,这样你只需要逗号就可以了。仅在循环外打印$category

<?php 
    $abcd = $mysqli->query("SELECT * FROM categories ");
    while ($obj = $abcd->fetch_object()) {                   
      $category = $obj->name;
      $results = $mysqli->query("SELECT * FROM `sub-category` WHERE category = '$category' ");     

       echo $category.': ';

       $subcats = array();
       while ($omg = $results->fetch_object()) {
         $subcats[] = $omg->subcategory;
       }

       echo implode(',', $subcats).'<br>';
    }
?>

答案 1 :(得分:0)

使用简单的JOIN

<?php 
    $abcd = $mysqli->query('SELECT DISTINCT categories.name,sub-category.subcategory FROM `categories` JOIN `sub-category` ON category.name = categories.category;');
    while($obj = $abcd->fetch_object())
    {
        echo $obj->name.' '.$obj->subcategory.'<br>';
    }
?>