duanhuancong1969 2016-05-29 16:27
浏览 18
已采纳

从MySQL查询中“分组”PHP结果

I'm having difficulty achieving this one, so thought I'd ask..

I have a table which contains some field names. Each field entry in the table has a type, a name and an ID as per the norm.

I'd like to be able to group my SQL results so that I can 'print' each type (and the type's associated members) into a table. I tried the following:

$query = "SELECT id,type,opt_name FROM fields ORDER BY type";  
$resource = $pdo->query($query);
$results = array();
while ( $row = $resource->fetch() ) {   
$type[$row['type']] = $row['opt_name'];
$o_id = clean($row['id'], 'text');
$o_name = clean($row['opt_name'], 'text');
}

foreach ($type AS $o_type => $o_name) {
    echo $o_type;
    echo "<br>";

    foreach (($type) AS $opt_name) { 
        echo $opt_name;
        echo "<br>";
         }
 }

Please try not to worry too much about the HTML output, it's just for this example to show context.

When the code is executed, it will only print one row. As a result, I have 'print_r' tested both:

$type[$row['type']] = $row['opt_name'];

Which does indeed show only one row in the array. Creating:

$results = $row;

Shows all the data, but too much of it and not in the way I think will work with the 'foreach'.

I'm probably making a rookie mistake here, but can't see it.

Help!

  • 写回答

1条回答 默认 最新

  • dtzjvj3915 2016-05-29 16:46
    关注

    You're going to be overwriting the value of $type['type'] instead of pushing more values onto it with:

    $type[$row['type']] = $row['opt_name'];
    

    You most likely want

    $type[$row['type']][] = $row['opt_name'];
    

    Then you'll need to fix your loop so you loop through the options, not the types twice.

    foreach ($type AS $o_type => $options) {
        echo $o_type;
        echo "<br>";
    
        foreach ($options AS $opt_name) { 
            echo $opt_name;
            echo "<br>";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计