2014-01-29 184 views
0

我得到這樣的例子:從查詢創建在一個while循環的關聯數組

<?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

是你在找這個?這將給您帶來像您展示的那樣的結構的預訂。

$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 />"; 
} 
+0

的查詢將返回'行x'數。所以我想說明這一點。對我來說,這看起來像是每次迭代都會重新創建數組,並且在完成時只包含查詢中的最後一行。 –

+0

如果這是從查詢返回多少行,它將創建帶有'x'個元素的$保留。 – mseifert

+0

好的。如何訪問一行?例如,在我的第一個示例中,人們可以像這樣訪問數據: 'for($ row = 0; $ row <3; $ row ++) { echo $ shop [$ row] [「Title」]。「costs 「$ shop [$ row] [」Price「]」,你就會得到「$ shop [$ row] [」Number「]; echo「
」; }' –

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; 

意味着$保留是一個數組,我們將追加該陣列$行上的下一個鍵($預約[下一關鍵] = $行)

+0

你將如何訪問數據? –

+0

例如:$ reservations [0] ['name'] – Djidel

+0

謝謝。答案轉到第一響應者身上,但我最終可能會因爲簡單而無法使用你。 –