从查询中创建while循环中的关联数组

时间:2014-01-29 21:00:59

标签: php mysql sql arrays

我得到了这个例子:

<?php 
$shop = array( array( Title => "rose", 
                  Price => 1.25,
                  Number => 15 
                ),
           array( Title => "daisy", 
                  Price => 0.75,
                  Number => 25,
                ),
           array( Title => "orchid", 
                  Price => 1.15,
                  Number => 7 
                )
         );
?>

但是我如何使用以下结构制作其中一个:

$result2 = mysqli_query($con, "SELECT r.id AS id, CONCAT(g.fname,' ',g.lname) AS name,
                                    r.arrival AS arrival, r.departure AS departure 
                                    FROM reservations r JOIN guests g ON r.guest = g.id
                                    WHERE r.unit = ".$unit_id."");

while ($row2 = mysqli_fetch_assoc($result2))
    {
        $reservations = array(  array (id => $row['id'],
                                      name => $row['name'],
                                      arrival => $row['arrival'],
                                      departure => $row['departure'],
                                    ));

    }

2 个答案:

答案 0 :(得分:2)

你正在寻找这个吗?这将为$ reservations提供与您展示的结构类似的结构。

$result2 = mysqli_query($con, "SELECT r.id AS id, CONCAT(g.fname,' ',g.lname) AS name,
                                    r.arrival AS arrival, r.departure AS departure 
                                    FROM reservations r JOIN guests g ON r.guest = g.id
                                    WHERE r.unit = ".$unit_id."");

$reservations = array();  // makes sure the array exists in case result set is empty
while ($row = mysqli_fetch_assoc($result2))
    {
        $reservations[] =   array (id => $row['id'],
                                      name => $row['name'],
                                      arrival => $row['arrival'],
                                      departure => $row['departure'],
                                    );

    }

访问如下:

foreach ($reservations as $row){
    echo $row["name"]." arrival ". $row["arrival"]; 
    echo "<br />"; 
}

您还可以访问:

for ($row = 0; $row<count($reservations); $row++){
    echo $reservations[$row]["name"]." arrival ". $reservations[$row]["arrival"]; 
    echo "<br />"; 
}

答案 1 :(得分:1)

这个怎么样:

$result2 = mysqli_query($con, "SELECT r.id AS id, CONCAT(g.fname,' ',g.lname) AS name,
                               r.arrival AS arrival, r.departure AS departure 
                               FROM reservations r JOIN guests g ON r.guest = g.id
                               WHERE r.unit = ".$unit_id."");
while($row = mysqli_fetch_assoc($result2) $reservations[] =   $row;

这条指令:

$reservations[] = $row;

表示$ reservations是一个数组,我们将在下一个键上添加$ row这个数组($ reservations [next key] = $ row)