不,這不可能數組作爲直接從關係(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']);
是的。使用一個SQL連接:http://en.wikipedia.org/wiki/Join_%28SQL%29 – 2013-02-24 20:37:21
我知道SQL連接,但它不給結果數組在陣列..它給只是簡單的數組與關係 – 2013-02-24 20:49:02
這不是數據庫的故障。這是你的錯誤,因爲沒有正確地構建你的「獲取」代碼。 – 2013-02-24 20:50:54