简体   繁体   English

PHP/MySQL 查询结果

[英]PHP/MySQL Query Results

Having an issue with a query..my wscategories stores the main categories of an online store, and my wssubcategories table stores the sub categories of the table with the foreign key called "parentcategory".查询有问题..my wscategories 存储在线商店的主要类别,而我的 wssubcategories 表使用称为“parentcategory”的外键存储表的子类别。 I'm trying to list the main categories, with the subcategories underneath a la:我正在尝试列出主要类别,并在 la 下方列出子类别:

Tops最高额

T-Shirts T 恤

Wovens梭织

Sweaters毛衣

Pants裤子

Shorts短裤

Jeans牛仔裤

The query/result I wrote is the following:我写的查询/结果如下:

$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS   
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND  
b.parentcategory = a.id";
      $result = mysql_query($query) or die(mysql_error());
      while ($row = mysql_fetch_array($result))
      {

        echo $row['maincategory'];

        echo "<br/>";
        echo $row['smallcategory'];
        echo "<br/>";
      }

Which returns:返回:

Tops最高额

T-Shirts T 恤

Tops最高额

Sweaters毛衣

Tops最高额

Wovens梭织

Etc. I want the script to just display the main category once, and then the subcategories underneath vs. displaying it multiple times.等等。我希望脚本只显示一次主类别,然后是下面的子类别,而不是多次显示它。 Any help?有什么帮助吗?

try something like this尝试这样的事情

// note we need to order by maincategory for this to work
//
$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS   
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND  
b.parentcategory = a.id
ORDER BY maincategory ASC,
smallcategory ASC
";
      $result = mysql_query($query) or die(mysql_error());


      // keep track of previous maincategory
      $previous_maincategory = NULL;

      while ($row = mysql_fetch_assoc($result))
      {

        // if maincategory has changed from previouscategory then display it
        if ($previous_maincategory != $row['maincategory']) {
            echo $row['maincategory'];
        }

        echo "<br/>";
        echo $row['smallcategory'];
        echo "<br/>";

        // record what the previous category was
        $previous_maincategory = $row['maincategory'];
      }

Set a flag after you echo the main category, like this:在回显主类别后设置一个标志,如下所示:

$echoed_main = false;
while ($row = mysql_fetch_array($result)) {
    if (!$echoed_main) {
        echo $row['maincategory'];
        echo "<br/>";
        $echoed_main = true;
    }
    echo $row['smallcategory'];
    echo "<br/>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM