2013-02-24 39 views
0

是它得到結果像這樣從2個表productsproducts image關係表...越來越綜合作用的結果在SQL

我使用PHP的可能。我可以使用php來創建數據,但是我想使用sql來獲取這種形式的數據,因爲性能。我知道sql連接,但它提供了簡單的數組數據。我需要數組作爲數組。

Products表:

id name  
1 product1   
2 product2 

images表:

product_id imageid 
1   1 
1   2 
1   3 
2   4 
2   5 
2   6 


[0] => Array 
     (
      [id] => 1 
      [images] => Array 
       (
        [0] => 1 
        [1] => 2 
        [2] => 3 
       ) 

     ) 
[1] => Array 
     (
      [id] => 2 
      [images] => Array 
       (
        [0] => 4 
        [1] => 5 
        [2] => 6 
       ) 
     ) 
+0

是的。使用一個SQL連接:http://en.wikipedia.org/wiki/Join_%28SQL%29 – 2013-02-24 20:37:21

+0

我知道SQL連接,但它不給結果數組在陣列..它給只是簡單的數組與關係 – 2013-02-24 20:49:02

+0

這不是數據庫的故障。這是你的錯誤,因爲沒有正確地構建你的「獲取」代碼。 – 2013-02-24 20:50:54

回答

0

不,這不可能數組作爲直接從關係(SQL)數據庫中的結果中得到一個數組。

您需要遍歷結果並自己創建數組,例如,

$productsById = array(); 

foreach ($dbRows as $row) { 
    if (!isset($productsById[$row['product_id']])) { 
     $product = array(
      'id' => $row['product_id'], 
      'name' => $row['product_name'] 
     ); 
     //note the use of the & to set the $product array by reference 
     $productsById[$row['product_id']] = &$product; 
    } 
    //note the use of the & to retrieve the $product array by reference 
    else $product = &$productsById[$row['product_id']]; 

    $product['images'][] = array(
     'id' => $row['image_id'] 
    ); 

    //We unset this because we accessed it by reference above; this prevents referencing the wrong product 
    //on the next iteration of the loop. 
    unset($product); 
} 

或者,得到的對象數組:

$productsById = array(); 

foreach ($dbRows as $row) { 
    if (!isset($productsById[$row['product_id']])) { 
     $product = new stdClass; 
     $product->id = $row['product_id']; 
     $product->name = $row['product_name']; 
     $product->images = array(); 
     $productsById[$row['product_id']] = $product; 
    } 
    else $product = $productsById[$row['product_id']]; 

    $image = new stdClass; 
    $image->id = $row['image_id']; 
    $product->images[] = $image; 
} 

這也是值得一提的,但是,如果你使用MySQL(和數據庫的便攜性不是問題),你可以利用GROUP_CONCAT功能,例如:

SELECT p.id as product_id, p.name as product_name, GROUP_CONCAT(i.id) as image_ids 
FROM product p 
LEFT JOIN image i ON p.id = i.product_id 
GROUP BY p.id 
在你的PHP

然後,你必須爲每個產品只有一個$排陣,你可以通過使用獲得的圖像標識簡單:

$imageIds = explode(',', $row['image_ids']); 
+0

非常感謝你.. – 2013-02-25 01:59:12

+0

我的第一個例子中有一個錯誤;我現在糾正了它。 – 2013-02-25 02:06:16

+0

這當然假定每個產品都有圖像;如果沒有,你需要檢查'empty($ row ['image_id'])'來測試是否存在圖像ID,然後將它添加到圖像數組中。 – 2013-02-25 02:14:08