从两个表中检索数据到多维数组api json响应

时间:2015-03-25 16:13:47

标签: php multidimensional-array

我正在学习Api开发,我想从两个表中检索数据

第一个表(项目)包含:

id, feed_id, title, author, content

第二张表(供稿):

feed_id,title,url

我想让Json回复如下:

 {
      - stories :
            [
               id
               feed_id {
                          title,
                          url
                       }
               title
               author
            ]
}

我的PHP函数用于检索偏向于id的故事,如:

$app->get('/stories/:id', 'authenticate', function($story_id) { 
    $response = array();
    $result = Database::get('db')->table('items')
    ->eq('rowid', $story_id)
    ->findOne();
    //$response["error"] = false;
    if ($result != NULL) {
    $response['stories'] = array(
        'id' => $result["id"],
        'feed_id' => $result["feed_id"],
        'title' =>  $result["title"],
        'isBreaking' => $result['isBreaking'],
        'author' => $result['author'],
        'updated' => $result["updated"],
        'url' => $result['url'],
        'content' => $result["content"]);
         echoRespnse(200, $response);
    }
    else {
        $response["error"] = true;
        $response["message"] = "The requested resource doesn't exists";
        echoRespnse(404, $response);
    } 
});

我得到的结果是:

 {
   - "stories": [
             {
                id
                feed_id
                title
                url
             }
           ]
}

如何从Feed_id上偏向的第二个平板电脑(Feed)中检索数据并将数据转换为子数组?

1 个答案:

答案 0 :(得分:1)

正如@MikeBrant所提到的,你必须在两个表之间使用join来检索正确的数据。普通的查询将是这样的:

select items.id, items.title, items.author, items.content, feeds., feeds.title as feed_title, feeds.url from items left join feeds on items.feed_id = feeds.feed_id

然后像这样更改$response['stories']

$response['stories'] = array(
'id' => $result["id"],
'feed_id' => array(
  'title' => $result["feed_title"],
  'url' => $result["url"]
),
'title' =>  $result["title"],
.
.
.
);

你明白了这一点:)