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>";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法