我會用表連接簡化到這個返回單個陣列中的單個查詢,那麼陣列上使用json_encode(見http://www.php.net/manual/en/function.json-encode.php)
也許類似以下內容:
$userId = $_SESSION['userID'];
$query = "SELECT store.*, photos.*
FROM cart
INNER JOIN store ON store.itemid = cart.itemid
INNER JOIN photos ON photos.itemid = cart.itemid
WHERE cart.userid='$userId'";
echo json_encode(mysql_fetch_array(mysql_query($query)));
那被說,看到這篇文章爲什麼不使用mysql_函數: Why shouldn't I use mysql_* functions in PHP?
- EDIT--這是一個使用SQLite的例子;你可以改變它來匹配您要使用什麼數據庫:
$db = new SQLite3("db.db");
$query = "SELECT store.description, store.price, store.quantity, photos.photo_url
FROM cart
INNER JOIN store ON store.item_id = cart.item_id
INNER JOIN photos ON photos.item_id = cart.item_id
WHERE cart.user_id=1;";
$results = $db->query($query);
$full_array = array();
while ($row = $results->fetchArray())
{
$full_array[] = $row;
}
echo json_encode($full_array);
和輸出:
[
{
"0": "a",
"1": 1,
"2": 1,
"3": "/images/photo_1.jpg",
"description": "a",
"price": 1,
"quantity": 1,
"photo_url": "/images/photo_1.jpg"
},
{
"0": "b",
"1": 2,
"2": 2,
"3": "/images/photo_2.jpg",
"description": "b",
"price": 2,
"quantity": 2,
"photo_url": "/images/photo_2.jpg"
},
{
"0": "c",
"1": 3,
"2": 3,
"3": "/images/photo_3.jpg",
"description": "c",
"price": 3,
"quantity": 3,
"photo_url": "/images/photo_3.jpg"
},
{
"0": "d",
"1": 4,
"2": 4,
"3": "/images/photo_4.jpg",
"description": "d",
"price": 4,
"quantity": 4,
"photo_url": "/images/photo_4.jpg"
},
{
"0": "e",
"1": 5,
"2": 5,
"3": "/images/photo_5.jpg",
"description": "e",
"price": 5,
"quantity": 5,
"photo_url": "/images/photo_5.jpg"
}
]
有你這樣做完全3個單獨的查詢,而不是連接表的原因是什麼?顯而易見的是,用戶在購物車中有物品,商店中的物品有照片,並且該照片具有用於檢索該關係的itemID列。加入該關係而不是執行兩個甚至三個獨特的查詢會更有效率。 – skrilled
我是新來的PHP,我怎麼能簡化?知道我是從3個不同的行查詢數據。 – user3476925
不使用phps mysql,而是使用mysqli代替:http://stackoverflow.com/a/14110189/1612852 mysqli_query> mysql_query – stepquick