1

我在数据库上有 1 个表 :( SQL )

-- id
-- city_name
-- image

我想查看他们城市内的每张图片,例如:美国有 3 张图片,加拿大有 2 张,看起来像:

USA
image 01
image 02
image 03

CANADA
image 01
image 02

我试过这段代码,它将查看所​​有混合的记录

$results1 = mysql_query("SELECT * FROM gallery");
while($r = mysql_fetch_array($results1)) {

    echo $r[city_name]."<hr>";

    $city = $r[city_name];
    $results2 = mysql_query("SELECT * FROM gallery WHERE city_name='$city'");


    while($r = mysql_fetch_array($results2)){
        echo '<img border="0" src="'.$r['image'].'">';
    }
}

谢谢,

4

2 回答 2

1

更正您的代码:

您正在将第一个查询的 `result set $r 覆盖到第二个 while 循环中

    $last='';
    $results1 = mysql_query("SELECT * FROM gallery order by city_name ASC");
    while($r = mysql_fetch_array($results1)){

    if($last!=$r['city_name']) {    
    echo $r['city_name']."<hr>";
       $last = $r['city_name']; 
    }

    $city = $r['city_name'];

    $results2 = mysql_query("SELECT * FROM gallery WHERE city_name='$city'");


        while($r1 = mysql_fetch_array($results2)){ //change this variable

                    echo $r1['image'];

        }
   }

第二种解决方案:

$data = array();
$results1 = mysql_query("SELECT * FROM gallery");
while($r = mysql_fetch_array($results1)){
    $data[$r['city_name']][]=$r;
}
foreach($data as $key=>$images){
     echo $key.PHP_EOL; //city name
     foreach($images as $image){
         echo $image['id'].PHP_EOL; // each image id
         echo $image['image'].PHP_EOL; // each image for city
     }
}
于 2012-12-15T16:13:38.003 回答
0

只需一个查询即可简化您的代码。

<?php
$cityImages = array();
$res = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array($res)) {
 $cityImages[$row['city_name']][] = $row['image'];
};
?>

然后你可以使用 $cityImages 数组。

于 2012-12-15T16:19:20.017 回答