我正在为我的移动应用程序创建一个 API。我正在使用 PHP MYSQL 和 Slim 框架(这在很大程度上与这个问题无关)来开发它。
我正在尝试从我的 mysql 数据库中提取多个“场地”,并为每个“场地”检索多个“场地图像”。数据库:
venues venue_images
------ ------------
id PK image_venue_id FK (to venues)
venue_name image_path
active
然后我需要以这种格式输出数据:
{
"completed_in":0.01068,
"returned":10,
"results":[
{
"venue_id":"1",
"venue_name":"NameHere",
"images": [
{
"image_path":"http://www.pathhere.com"
},
{
"image_path":"http://www.pathhere2.com"
}
]
}
]
}
所以基本上,每个场地的图像都会重复多次。
我目前的代码是:
$sql = "
SELECT
venues.id, venues.venue_name, venues.active,
venue_images.image_venue_id, venue_images.image_path
FROM
venues
LEFT JOIN
venue_images ON venue_images.image_venue_id = venues.id
WHERE
venues.active = 1
LIMIT 0, 10
";
$data = ORM::for_table('venues')->raw_query($sql, array())->find_many();
if($data) {
foreach ($data as $post) {
$results[] = array (
'venue_id' => $post->id,
'venue_name' => $post->venue_name,
'images' => $post->image_path
);
}
//Build full json
$time = round((microTimer() - START_TIME), 5);
$result = array(
'completed_in' => $time,
'returned' => count($results),
'results' => $results
);
//Print JSON
echo indent(stripslashes(json_encode($result)));
} else {
echo "Nothing found";
}
我当前的代码有效,但是它产生了这个:
{
"completed_in":0.01068,
"returned":10,
"results":[
{
"venue_id":"1",
"venue_name":"The Bunker",
"images":"https://s3.amazonaws.com/barholla/venues/1352383950-qPXNShGR6ikoafj_n.jpg"
},
{
"venue_id":"1",
"venue_name":"The Bunker",
"images":"https://s3.amazonaws.com/barholla/venues/1352384236-RUfkGAWsCfAVdPm_n.jpg"
}
]
}
“The Bunker”有两张图片。它没有将图像存储在场地阵列中,而是使用第二个图像创建了“The Bunker”的重复行。就像我之前说的,我需要在每个场地内迭代多个图像。任何帮助将非常感激!谢谢!