我正在使用連接從兩個表中查詢數據。對於每個a_id,我需要獲取關聯的image_id,過濾這些image_id結果,以便只保留第一個結果,最後將結果輸出到li中。我認爲我的查詢很好,但是我在包裝我的頭部時遇到了一些麻煩,要如何爲每個a_id獲取image_id並將其輸出到我的li。此代碼返回一些結果,但它們不是我正在尋找的。帶連接表的2D數組
<?php
echo '<ul>';
$result = mysql_query ("SELECT * from artists left join images on artists.a_id = images.image_id where artists.display_works = '1' and artists.active = '1' order by artists.project_year desc, artists.fullname desc");
while ($row = mysql_fetch_array($result)){
$data['a_id']['image_id']=$row->a_id;
foreach($data as $id=>$images) {
$totalimages=1;
$addstyle = "";
$art_id = $data['a_id'];
$img_id = $data['image_id'];
foreach($images as $val){
if($totalimages > 1){ $addstyle = 'style="display:none;"'; }
else {
$myimagename = "http://artists/$art_id/images/$img_id" . "_large.jpg";
list($width, $height, $type, $attr) = getimagesize("$myimagename");
$myimagename = "http://artists/resize.php/$art_id/images/$img_id" . "_large.jpg?resize(157x2000)";
if($row["layout"] == "vert"){$pl = "_vertical";}else if($row["layout"] == "website"){$pl = "-s";}else if($row["layout"] == "video"){$pl = "_video";}else{$pl = "_horizontal";}
echo "<li class='thumbnail_container' $addstyle> <a class='thumbnail' href=\"../works$pl.php?a_id=" . $row["a_id"] . "\"><span><img src=\"$myimagename\" /></span>\n</a></li>\n";
}
$totalimages++;
}
}
}
echo '</ul>';
?>
嗯,我已經修改了代碼位和它的工作,但由於某種原因,我沒有圖像的URL或鏈接URL的第一圖像後獲得一個額外的縮略圖。我認爲這可能與我的方法檢查重複的a_ids有關:
<?php
echo '<ul>';
$result = mysql_query ("SELECT * from artists left join images on artists.a_id = images.a_id where artists.display_works = '1' and artists.active = '1' order by artists.project_year desc, artists.fullname desc, images.position asc");
while ($row = mysql_fetch_array($result)){
$check = $row['a_id'];
if (in_array($check, $a_ids)) {end;}
else {
$a_id=$row['a_id'];
$a_ids[] = $a_id;
$image_id=$row['image_id'];
$myimagename = "http://artists/$a_id/images/$image_id" . "_large.jpg";
list($width, $height, $type, $attr) = getimagesize("$myimagename");
$myimagename = "http://artists/resize.php/$a_id/images/$image_id" . "_large.jpg?resize(157x2000)";
if($row["layout"] == "vert"){$pl = "_vertical";}else if($row["layout"] == "website"){$pl = "-s";}else if($row["layout"] == "video"){$pl = "_video";}else{$pl = "_horizontal";}
echo "<li class='thumbnail_container' $addstyle> <a class='thumbnail' href=\"../works$pl.php?a_id=" . $row["a_id"] . "\"><span><img src=\"$myimagename\" /></span>\n</a></li>\n";
}
}
echo '</ul>';
?>
你爲什麼要處理各行的結果裏面的取環?完整的數據庫結果將不可用,所以無論這種過濾應該無法正常工作。 – 2012-02-18 02:48:16
我應該在哪裏移動它?更重要的是它是正確的? – 2012-02-18 03:00:39
將它移到while()循環之外。至於正確,不知道。我無法告訴你想要完成什麼。就目前而言,您從數據庫中獲取一行數據,然後遍歷您迄今爲止獲取的所有內容。然後你再取一行,再遍歷每一個字母,等等。你是一個[Schlemiel](http://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm) – 2012-02-18 03:07:18