我有以下表格:
+---------+-----------+ +----------+---------+-------------+
| item_id | item_name | | image_id | item_id | image_url |
+---------+-----------+ +----------+---------+-------------+
| 1 | phone | | 1 | 1 | http://url1 |
| 2 | computer | | 2 | 1 | http://url2 |
| 3 | keyboard | | 3 | 2 | http://url2 |
+---------+-----------+ +----------+---------+-------------+
我应该在php中使用PDO和json编码进行以下输出:
[
{
"item_id":"1",
"name":"phone",
"images": [
{
"image_id":"1",
"url":"http://url1"
},
{
"image_id":"2",
"url":"http://url2"
}
]
},
{
"item_id":"2",
"name":"computer",
"images": [
{
"image_id":"3",
"url":"http://url3"
}
]
},
{
"item_id":"3",
"name":"keyboard",
"images": []
}
]
我是否必须在 foreach 循环中使用 foreach 来获得此结果?
答案 0 :(得分:0)
不,使用单个循环和单个SQL查询。
首先,SQL查询是
SELECT im.image_id, im.image_url, im.item_id
it.item_name
FROM images im
LEFT JOIN items it ON it.item_id=im.item_id
ORDER BY im.item_id, im.image_id
你的PHP(释义)是:
$lastItemId = -1;
$aJson = array();
while ($row = GetNextRow()) { // Depends on your class
$itemID = $row['item_id'];
if (!isset($aJson[$itemID])) {
$aJson[$itemID] = array('item_id'=$itemID, 'item_name'=$row['item_name'], images=>array());
}
$aJson[$itemID]['images'] = array('image_id'=>$row['image_id'], 'image_url'=>$row['image_url']);
}
echo json_encode($aJson);
您应该可以从那里进行调整吗?