我正在尝试从数据库中获取数据,并希望按该 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/