php - 按公共(public) ID 分组

标签 php mysql sql

我正在尝试从数据库中获取数据,并希望按该 ID 对名为 order_ids 的列中的常见值进行分组。

这是我当前获取数据的状态

Order_Id      |    Product Name

-------------------------------
  10001       |    iPhone 5
  10001       |    Blackberry 9900
  10002       |    Galaxy S
  10003       |    Rhyme
  10004       |    Google Nexus
  10005       |    Razr
  10006       |    iPad Air

这就是我想要的状态

Order_Id      |    Product Name

-------------------------------
  10001       |    iPhone 5
                   Blackberry 9900
  10002       |    Galaxy S
  10003       |    Rhyme
  10004       |    Google Nexus
  10005       |    Razr
  10006       |    iPad Air

这是我在 Controller 文件中获取结果的方法

    foreach($results_query as $results_custom) {
        $this->data['result_custom'][] = array(
            'model' => $results_custom['product_name'],
            'order_number' => $results_custom['order_id']
        );
    }

这是我在 View 文件中显示它的方式

 <?php foreach ($results_custom as $result) { ?>
 <li><?php echo $result['model']; ?></li> <br />
 <li><?php echo $result['order_number']; ?></li><br />
 <?php } ?>

是否可以使用 SQL 或 PHP 让我的数据以这种方式显示或以那种状态显示?如果您也想查看我的查询,请告诉我。

最佳答案

在 php 中会更容易做到。由于我没有 PHP 环境来测试它,我将向您展示一些执行此操作的逻辑。 不一定是工作代码。那是因为你没有提供你所做的

<?
  $sql = "select order_id, product name from ..... order by order_id"// rest of sql code ....
  //here you iterate your results
  $previousId = ""; //var to store previous id
  while( $fetch... ){
      if ( $fetchedID != $previousId ){
        echo $fetchedId . "-" . $fetchedProductName;
      }else{
        echo $fetchedProductName;
      }
      $previousId = $fetchedID;
  }
?>

这应该可以。 当您更新代码时,这就是适合您的解决方案:

<?php 
   $lines = ""; //to make code cleaner;
   $previousModel = "";
   foreach ($results_custom as $result) {
     if ( $previousModel != $result['model'] ){ 
         $line .= "<li>" .  $result['model'] . "</li>";
     }else{
         $line .= "<li></li>";
     }   
     $line .= "<li>" . $result['model'] . "</li><br />";
     $previousModel = $result['model'];
   }
   echo $line;
 <?php } ?>

关于php - 按公共(public) ID 分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19732150/

相关文章:

php - htmlentities() 期望参数 1 为字符串,数组给定

c# - 统一 WebGL : can I access to MySql using MySqlConnector?

mysql - docker,无法启动从官方 docker 镜像 mysql 构建的 docker mysql 容器

mysql - 左连接查询问题

sql - Postgres : one table with many columns or several tables with fewer columns?

php - 分页在 Yii 框架中不起作用

php - 将请求注入(inject) Symfony2 实体

php - 我的登录 PHP 脚本出现故障

javascript - 动态添加表单,可以插入到sql表中

php - 通过 Apache 在所有页面中插入 HTML 代码?