【问题标题】:php, json_encode, nested arrays w/ one "left join" queryphp,json_encode,嵌套数组,带有一个“左连接”查询
【发布时间】:2012-01-21 06:20:53
【问题描述】:

我有一个带有相应“cmets”表的“post”表(每个“comment”行都有一个与“post”表相关的“post_id”)。

这是我的函数,它从我的查询中回显我的 JSON 响应:

function echo_json_result($result) {

$arr = array();

while($row = mysql_fetch_assoc($result)) {

$arr[] = $row;

}

echo json_encode($arr);

}

目前这会吐出一个大数组。

为了响应的可读性,我希望将与这些“帖子”关联的“cmets”作为嵌套数组返回。

我可以想到一种方法来做到这一点。创建两个查询,一个用于注释,一个用于与注释关联的所有 cmets。然后,将包含所有 cmets 的关联数组添加到 notes 数组,然后对其进行 json_encode。

这是最好的方法吗?

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    尝试这样的事情,但帖子需要在您的 cmets 之前出现在结果中:

    function echo_json_result($result) {
    
        $arr = array();
    
        while ($row = mysql_fetch_assoc($result)) {
            if( $row['post_id'] != "" )
            {
                 if( array_key_exists("comments", $arr['post_id']) )
                 {
                     array_push($arr['post_id']['comments'], $row);
                 }
                else
                {
                     $arr['post_id']['comments'] = array($row);  
                }
            }
            else
            {
                $arr[$row['id']] = $row;
            }
        }
    
        echo json_encode($arr);
    
    }
    

    【讨论】:

      【解决方案2】:

      这是 ORM 可以做的工作。例如,我举了a bunch of class 的工作,没有深度限制。提供了一个映射字段和所需嵌套数组的数组参数:

      例如:

      SELECT article.name, article.id as id, comment.id as comment_id, comment.value FROM article JOIN comment ON comment.article_id = article.id

      以及对应的映射数组:

      $mapping = [ 'id', 'name', 'comments' => ['id','value']];
      

      【讨论】:

        猜你喜欢
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        • 2012-04-10
        • 2021-01-14
        • 2021-02-21
        • 1970-01-01
        • 2014-10-07
        • 1970-01-01
        相关资源
        最近更新 更多