我想把一个while循环放入一个数组中

时间:2013-11-22 15:30:30

标签: php mysql arrays loops multidimensional-array

我有一个多维数组,在"images"下我想从我的数据库中循环4行。这意味着我正在尝试将循环放入数组中。帮助我。

$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());

$albums = array();

while ($row_album = mysql_fetch_assoc($res_album)) {
    $albums[$row_album['title']] = array(
        "description" => $row_album['description'], 
        "date" => $row_album['date'], 
        "images" => array(
            //i want to insert a loop here shown down
        )
    );
}

这是我要插入的循环,我在上面的脚本中写了注释:

$sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
$res_thumb = mysql_query($sql_thumb) or die(mysql_error());

while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
    echo $row_thumb['thumb_url'];
}

2 个答案:

答案 0 :(得分:3)

从这里开始......

include('../path/to/mysqli/connection/statements');

$query = "
SELECT a.id
     , a.title
     , a.description
     , a.date
     , p.thumb_url
  FROM albums a
  LEFT
  JOIN photos p
    ON p.album_id = a.id
 ORDER
    BY a.id;
";

$result = mysqli_fetch_assoc($db,$query);

答案 1 :(得分:0)

可悲的是,PHP不允许这种用法。但是你可以这样做

$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());

$albums = array();

while ($row_album = mysql_fetch_assoc($res_album)) {
    $albums[$row_album['title']] = array(
        "description" => $row_album['description'], 
        "date" => $row_album['date'], 
        "images" => array()
    );

    $sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
    $res_thumb = mysql_query($sql_thumb) or die(mysql_error());

    while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
        $albums[$row_album['title']]["images"][] = row_thumb['thumb_url'];
    }
}