簡體   English   中英

在關聯數組中左連接

[英]left join in an associative array

我正在嘗試制作圖片庫。 有其中包含圖像的相冊,並且在索引頁面上,我想顯示其中的女巫相冊,當您單擊它時,便轉到該相冊。 我可以顯示相冊名稱,但是我想使用隨機功能將這些相冊與該相冊內的圖像一起顯示。 我希望你了解我想做什么。 問題是我無法到達圖像。

我有兩個關聯數組,一個用於相冊,一個用於圖像。 一張專輯看起來像這樣;

function get_albums() {
$albums = array();

$albums_query = mysql_query("
SELECT `albums`.`album_id`, `albums`.`timestamp`, `albums`.`name`,     
LEFT(`albums`.`description`, 50) as `description`, COUNT(`images`.`image_id`) as `image_count`
FROM `albums`
LEFT JOIN `images`
ON `albums`.`album_id` = `images`.`album_id`
GROUP BY `albums`.`album_id`
")or die(mysql_error());

while ($albums_row = mysql_fetch_assoc($albums_query)) {
    $albums[] = array(
        'id' => $albums_row['album_id'],
        'timestamp' => $albums_row['timestamp'],
        'name' => $albums_row['name'],
        'description' => $albums_row['description'],
        'count' => $albums_row['image_count']       
        );
}

return $albums;
}

對於圖像,看起來像這樣;

function get_images($album_id) {
$album_id = (int)$album_id;

$images = array();

$image_query = mysql_query("SELECT `image_id`, `image_name`, `album_id`, `timestamp`, `ext` FROM `images` WHERE `album_id`=$album_id");
while ($images_row = mysql_fetch_assoc($image_query)) {
    echo $images_row['image_id'];

    $images[] = array(
    'id' => $images_row['image_id'],
    'img_name' => $images_row['image_name'],
    'album' => $images_row['album_id'],
    'timestamp' => $images_row['timestamp'],
    'ext' => $images_row['ext']
    );
}
return $images;
}

我以為在get_albums函數中,通過左連接函數,我可以通過添加圖像名稱和擴展名來到達圖像,如下所示:

while ($albums_row = mysql_fetch_assoc($albums_query)) {
    $albums[] = array(
        'id' => $albums_row['album_id'],
        'timestamp' => $albums_row['timestamp'],
        'name' => $albums_row['name'],
        'description' => $albums_row['description'],
        'count' => $albums_row['image_count'],
        'img_name' => $albums_row['image_name'],
        'ext' => $albums_row['ext']         
        );   

然后像這樣在索引頁面中使用它;

$albums = get_albums();

if (isset($albums)) {
foreach ($albums as $album) {
    echo '<a href="view_album.php?album_id=', $album["id"], '"><img src="uploads/thumbs/', $album["id"] ,'/', $album['img_name'],'.', $album["ext"],'" />', $album['name'], '</a>';
}
}

但是結果是這樣; http://www.robcnossen.nl/

我究竟做錯了什么?

為什么不進行一個大型查詢,使其首先連接所有數據,然后按您的意願顯示它,如下所示:

sql="SELECT * FROM albums a INNER JOIN images i ON a.album_id = i.album_id WHERE a.album_id =" . $album_id;

$result = mysql_query(sql);

while ($row = mysql_fetch_array($result))  {
     echo '<a href="view_album.php?album_id=' . $row['album_id'] . '><img src="uploads/thumbs/' . $row['album_id'] . '/' . $row['album_id'] . '.' . $row['album_ext'] . '" />' . $row['album_name'] . '</a>';
}

然后它應該准確顯示您想要的方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM