duannuan0074 2016-01-23 05:03
浏览 25
已采纳

在php中显示每种类型的组的mysql数据

I have my table structure like as below:

tbl1

id  prodid prodname height cost category
-----------------------------------------
 1    1     Test      5     54    ABC
 2    5     Test1     6     85    DEF
 3    8     Test2     8     20    DEF
 4    2     Test3     4     10    GHI
 5    3     test4     8     58    ABC
 6    4     Test5     84    878   ABC

tbl2

 id(FK of pid)   color intensity vibrance
-----------------------------------------
  1                 red   5        NA
  5                 pink  0.5      8 ..and so on

Now i want the output like as below,

Want Output

ABC
----
 Test ... & other parameters
 test4 ... & other parameters
 Test5 ... & other parameters
DEF
---
 Test1 ... & other parameters
 Test2 ... & other parameters
GHI
----
 Test3 ... & other parameters

Query I have tried is:

"SELECT tbl1.*,tbl2.* from tbl1 LEFT JOIN tbl2 on tbl1.prodid=tbl2.id;

PHP

i tried to show cat as below:

$category="";
foreach($all as $row){
  if ($row['category'] != $category && !empty($row['category'])) {
        echo $row['category']; $category=$row['category'];
  }
  echo $row['othercolumns'];
}

But it is not grouping... It is repeating every time.

  • 写回答

2条回答 默认 最新

  • donglingyi4679 2016-01-23 05:40
    关注

    You can use PDO, which has a nice feature for you with PDO::FETCH_GROUP option in PDOStatement::fetchAll() function. Firstly in your query, make category the first column, like this way :

    SELECT tbl1.category, tbl1.* from tbl1 LEFT JOIN tbl2 on tbl1.pid=tbl2.id;
    

    Then run the query in PDO and fetchAll with PDO::FETCH_GROUP

    $sth = $dbh->prepare($query);
    $sth->execute();
    $result = $sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
    print_r($result); 
    
    //Result will be something like this:
    
    Array (
        [ABC] => Array
            [0] => Array
                (
                   [id] => 1,
                   [prodid] => 1,
                   [prodname] => "test",
                   [height] => 5,
                   [cost] => 54,
                   [category] => "ABC",
                ),
            [1] => Array
                (
                 ...
                ),
            ....
            ),
        [DEF] => Array
            (
             ...
            ),
        ....
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分