代码之家  ›  专栏  ›  技术社区  ›  sam

php&mysql:将group by用于类别

  •  6
  • sam  · 技术社区  · 15 年前

    我的数据库有以下设置

    productid | productname | category id
    

    我想像这样输出它们:

    category #1
    item 1 
    item 2
    item 3
    
    category #2
    item 1 
    item 2
    item 3
    

    我使用分组方式将它们组合在一起,这很好,但是我想循环遍历每个组并显示该组的内容。我该怎么做?

    6 回复  |  直到 15 年前
        1
  •  16
  •   Bill Karwin    11 年前

    我建议只使用一个简单的查询来获取所有行,并按类别ID排序。只有当类别的值与前一行的值不同时,才输出该类别。

    <?php
    
    $stmt = $pdo-> query("SELECT * FROM `myTable` ORDER BY categoryID");
    
    $current_cat = null;
    while ($row = $stmt->fetch()) {
      if ($row["categoryID"] != $current_cat) {
        $current_cat = $row["categoryID"];
        echo "Category #{$current_cat}\n";
      }
      echo $row["productName"] . "\n";
    }
    
    ?>
    
        2
  •  8
  •   qwerty_so Rainier Wolfcastle    10 年前

    这应该有效:

    $categories = array();
    $result= mysql_query("SELECT category_id, product_name  FROM `table` GROUP BY `catagory_id` ORDER BY `catagory_id`");
    while($row = mysql_fetch_assoc($result)){
        $categories[$row['category_id']][] = $row['product_name'];
    }
    
    // any type of outout you like
    foreach($categories as $key => $category){
        echo $key.'<br/>';
        foreach($category as $item){ 
            echo $item.'<br/>';
        }
    }
    

    你可以自己设计的输出。只需将所有内容添加到一个多维数组中,类别ID作为第一级键。

    编辑 :结果数组可能如下所示:

    $categories = array(
        'cateogy_id_1' => array(
            1 => 'item_1',
            2 => 'item_2',
            ...
        ),
        'cateogy_id_2' => array(
            1 => 'item_1',
            2 => 'item_2',
            ...
        ),
        ....
    );
    
        3
  •  2
  •   Marcus Adams    15 年前

    你想要的是按类别排序,而不是按组排序。

    SELECT * FROM MyTable
    ORDER BY category_id, product_id
    

    当您遍历列表时,只要在类别_id更改时输出一个新的头。

        4
  •  2
  •   2MAS    9 年前

    这种方法不需要按类别ID对数据进行排序。

    您可以使用PHP将每个类别分组在一个嵌套数组中。 之后,数据可以很容易地显示在表中,传递到图形/图表库等。

    <?php
    $stmt = $pdo-> query("SELECT * FROM myTable ORDER BY categoryID");
    
    
    $categories = []; //the array to hold the restructured data
    
    //here we group the rows from different categories together
    while ($row = $stmt->fetch())
    {
        //i'm sure most of you will see that these two lines can be performed in one step
        $cat = $row["categoryID"]; //category id of current row
        $categories[$cat][] = $row; //push row into correct array
    }
    
    //and here we output the result
    foreach($categories as $current_cat => $catgory_rows)
    {
        echo "Category #{$current_cat}\n";
    
        foreach($catgory_rows as $row)
        {
            echo $row["productName"] . "\n";
        }
    }
    ?>
    
        5
  •  0
  •   cbednarski    15 年前

    最简单的方法可能是提取类别列表,迭代并提取其附加产品。(即几个问题。)

    例如(伪代码):

    $result = fetch_assoc("SELECT category_id FROM categories");
    foreach($result as $row)
    {
      echo $row['category_id'];
      $result2 = fetch_assoc("SELECT product_id FROM products");
      foreach($result2 as $row2)
      {
        echo $row2['product_id'];
      }
    }
    

    如果您想在一个查询中完成这一切,可以执行如下操作:

    $result = fetch_assoc("SELECT product_id, category_id FROM products p JOIN categories c ON p.category_id = c.category_id ORDER BY c.category_id ASC");
    $last = null;
    foreach($result as $row)
    {
      # Output the category whenever it changes
      if($row['category_id'] != last)
      {
        echo $row['category_id'];
        $last = $row['category_id'];
      }
      echo $row['item_id'];
    }

    然后,您可以对结果集进行迭代,并在类别名称发生更改时将其拉出。

    在从数据库中获取SQL之前,可能有一种更复杂、更优雅的方法来编写它来完成所有工作,但我并不那么聪明。;)

    注意:示例使用伪代码。我使用的mysql抽象类的工作方式如下:

    $db->query("SELECT stuff");
    $db->multi_result(); // returns 2d-associative array

    那时我可以 foreach($db->multi_result() as $row) 太懒了,太棒了。

    如果您愿意,我可以发布抽象层的代码。

        6
  •  0
  •   suraj kumar    7 年前
    $stmt = $dbConnection->prepare("SELECT exam_id, COUNT(report_id) FROM bug_report GROUP BY exam_id; ");
            //$stmt->bind_param('s',$exam_id); 
            $stmt->execute();
            $extract = $stmt->get_result();
            $count = $extract->num_rows;
            if($count){
                while($rows = $extract->fetch_assoc()){
                    $exam_id = $rows["exam_id"];
                    switch($exam_id){
                        case "jee_questions":
                            $jeeBugCount = $rows["COUNT(report_id)"];
                            break;
                        case "gate_questions":
                            $gateBugCount = $rows["COUNT(report_id)"];
                            break;
                    }
                }   
            }