dqly83915
dqly83915
2018-08-29 19:26

嵌套的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 duanpan3166 3年前

    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.

    点赞 评论 复制链接分享