doushangan3690 2016-07-15 15:26
浏览 297
已采纳

MySQL:请求使用Array创建JSON对象

Ok, I have a simple question... I have a database with two tables :

Articles (id, content, title, date)

Comments (id_article, username, content)

And I want to obtain a JSON array like this :

[
    {
    "id": "5785634a87c5a0075bf211de",
    "title": "Elita",
    "content": "Commodo ea enim dolor enim adipisicing ut mollit .",
    "date":"15July2016"
    "comments": [
        {
        "username": "Tran",
        "content": "Ea aliqua sit fugiat adipisicing."
        },
        {
        "username": "Noreen",
        "content": "Commodo qui ea nulla est officia. non."
        },
        {
        "username": "Gilliam",
        "content": "Esse cupidatat adipisicing sit minim."
        }
    ]
    }
]

So my question ... Is it possible with only one request? :) Thanks you

  • 写回答

2条回答 默认 最新

  • douyi02577 2016-07-15 16:07
    关注

    You can LEFT JOIN to get all the data you need, when iterating over it you just have to take care about how you handle which data.

    $lastArticleId = null;
    $comments = [];
    $elements = [];
    $sql = 'SELECT Articles.*, Comments.content AS comment, Comments.username FROM Articles LEFT JOIN Comments ON Articles.id = Comments.id_article';
    $result = $pdo->query($sql);
    foreach ($result->fetchAll(PDO::FETCH_OBJ) as $dataset) {
        if($lastArticleId !== $dataset->id){
            $lastArticleId = $dataset->id;
            $elements[$lastArticleId] = [
                'id'       => $dataset->id,
                'title'    => $dataset->title,
                'content'  => $dataset->content,
                'date'     => $dataset->date,
                'comments' => [],
            ];
        }
        $comments[$lastArticleId][] = [
            'content' => $dataset->comment,
            'username' => $dataset->username,
        ];
    }
    foreach ($elements as $key => $article) {
        $article['comments'] = $comments[$key];
        $fullData[] = $article;
    }
    echo json_encode($fullData);
    

    But: Just because you can, doesn't mean you should.

    Splitting this task in two queries is a lot easier to write and to read. So if you later for some reason need to touch this piece of code (or someone else) he will be glad you chose the 2 query approach.

    Also it is good practice to split tasks, so ideally you would create methods in your database-access-layer getAllArticles() and another one getCommentsByArticleId($id_article). This way you could fetch all the comments, without having to load the whole article.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码