dqly83915 2018-08-29 19:26
浏览 73
已采纳

嵌套的PHP while循环在显示请求的结果之前返回先前的结果

I'm working on a double while loop in PHP to show results from a MySQL database in a grouped manner. This is an example of my database structure:

id name team country
1 Hamilton mercedes uk
2 Button mclaren uk
3 Alonso mclaren es
4 Perez mclaren mx

I want it displayed grouped like this:

ES  
Alonso  

MX  
Perez  

UK  
Button  
Hamilton

However my nested loop doesn't get any better than this:

ES  
Alonso

MX  
Alonso  
Perez  

UK  
Alonso  
Perez  
Button  
Hamilton

My loop is failing somewhere or I'm just taking the wrong approach. I tried increments, unnested loops, resetting vars, continue/break, but I can't figure it out. The first loop is to print a table structure per grouping. This is an example of my code:

<?php 

// count unique country entries 
$categories = $db->query("  
SELECT DISTINCT country
FROM cms_drivers
WHERE team = '$team'
ORDER BY country
");

while ($cat = $db->fetch_array($categories)) { // loops 3 times  
$custom = $db->query("
    SELECT id, name, team, country
    FROM cms_drivers
    WHERE team = '$team' AND country = '$cat[country]'
    ORDER BY name
");

while ($content = $db->fetch_array($custom)) {
    process('$drivers_bits .= "' . fetch_template('cms_drivers_bits') . '";');
}

process('$drivers .= "' . fetch_template('cms_drivers') . '";');

}

Am I overlooking something really simple or is this just the wrong approach?

cms_drivers_bits template:

<tr><td>$content[name]</td></tr>

cms_drivers template:

<table cellpadding="8" cellspacing="0" width="100%">  
<thead>  
<tr>  
<td class="header">  
<span><strong>$cat[country]</strong></span></td>  
</tr>  
</thead>  
<tbody>  
$drivers_bits  
</tbody>  
</table>  
  • 写回答

1条回答 默认 最新

  • duanpan3166 2018-08-29 20:19
    关注

    Based on what you're getting it looks like you just need to initialize $drivers_bits to an empty string before the inner loop.

    $drivers_bits = '';
    while ($content = $db->fetch_array($custom)) { ...
    

    $drivers_bits is probably used in fetch_template('cms_drivers'), and you're appending values to it each time rather than resetting it to the new values for that loop iteration.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集