php while循环选择类别

时间:2012-12-15 16:08:49

标签: php for-loop while-loop categories

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

-- id
-- city_name
-- image

我希望查看其中的所有图像,例如:USA有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'].'">';
    }
}

谢谢,

2 个答案:

答案 0 :(得分:1)

代码中的更正:

你将第一个查询的结果集$ 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
     }
}

答案 1 :(得分:0)

使用一个查询简化您的代码。

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

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