简体   繁体   English

如何从这个多维数组中形成JSON

[英]How to form JSON from this multidimensional array

My query returns the following: 我的查询返回以下内容:

post_id    post_type    post_text
1          text         bla1
2          pic          bla2
3          text         bla3

I loop through this result as follows: 我按如下方式遍历此结果:

$posts = array();
foreach ($query->result() as $row) {
    $post = array();
    $post['post_id']         = $row->post_id;
    $post['post_type']       = $row->post_type;
    $post['post_text']       = $row->post_text;
    $posts[] = $post;
}
$data['posts'] = $posts;

return $data;

If I json_encode and output from my controller I get this: 如果我从我的控制器json_encode和输出我得到这个:

{
    "stream": {
        "posts": [{
            "post_id": "1",
            "post_type": "text",
            "post_text": "bla1",
        },
        {
            "post_id": "2",
            "post_type": "pic",
            "post_text": "bla2",
        },
        {
            "post_id": "3",
            "post_type": "text",
            "post_text": "bla3",            
        }]
    }
}

However if a post has comments, my query returns 但是,如果帖子有评论,我的查询会返回

post_id    post_type    post_text    comment_id    comment_text
1          text         bla1         7             asd
1          text         bla1         8             sdf
2          pic          bla2
3          text         bla3         10            rty
3          text         bla3         11            yuo

How should I set up the foreach loop to build an array that will output JSON like this? 我应该如何设置foreach循环来构建一个像这样输出JSON的数组?

{
    "stream": {
        "posts": [{
            "post_id": "1",
            "post_type": "text",
            "post_text": "bla1",
            "comment": [{
                "comment_id": "7",
                "comment_text": "asd",
            },
            {
                "comment_id": "8",
                "comment_text": "sdf",
            }],
        },
        {
            "post_id": "2",
            "post_type": "pic",
            "post_text": "bla2",
        },
        {
            "post_id": "3",
            "post_type": "text",
            "post_text": "bla3",            
            "comment": [{
                "comment_id": "10",
                "comment_text": "rty",
            },
            {
                "comment_id": "11",
                "comment_text": "yuo",
            }],
        }]
    }
}

This JSON is consumed on Secha framework as follows: 这个JSON在Secha框架上使用如下:

                    proxy: {
                        type: 'jsonp',
                        url: 'http://myurl',
                        reader: {
                            type: 'json',
                            rootProperty: 'stream.posts'
                        }
                    }

Although I prefer to query each post individually for the existence of comments, here would be one attempt to construct the array using one query. 虽然我更喜欢单独查询每个帖子是否存在注释,但这里将尝试使用一个查询构造数组。

$posts=array();
$data = array();
foreach($query->result() as $row){
  // if the post hasn't been created in the array
  // create it
  if(!isset($posts[$row['post_id']])){
    $posts[$row['post_id']] = array(
      "post_type" => $row['post_type'],
      "post_text" => $row['post_text']
    );
  }
  // if a comment is found
  if(isset($row['comment_id'])){
    $posts[$row['post_id']]['comments'][] = array(
      "comment_id" => $row['comment_id'];
      "comment_text" => $row['comment_text'];
    );
  }

}
$data['posts'] = $posts;

JSON encoding this array would create something like... 对此数组进行JSON编码会产生类似......

{ "posts" :
   {
     1 : {
       "post_type" : "something",
       "post_text" : "something else"
     },
     2 : {
       "post_type" : "something",
       "post_text" : "something else",
       "comments" : [
         {"comment_id":1,"comment_text":"something"},
         {"comment_id":2,"comment_text":"something"}
       ]
     },
    ....
   }
 }

I cant vouch for this code completely working as I haven't tested it, but it should be a start. 我不能保证这个代码完全正常工作,因为我没有测试它,但它应该是一个开始。 Again, if I were you I'd just query each post individually. 再说一遍,如果我是你,我只是单独查询每个帖子。

I don't know PHP syntax so I wont write the code. 我不懂PHP语法,所以我不会写代码。 However this is not a PHP problem, but an algorithm problem. 然而,这不是PHP问题,而是算法问题。

What you could do to handle this data is doing it in three steps, with a intermediate result that would be a dictionary of posts. 您可以采取哪些措施来处理这些数据,分三步进行,中间结果是帖子字典。 In this dictionary, keys will be post ids, and values will be posts. 在这本词典中,键将是post id,值将是post。

1/ Iterate over the lines returned by your query. 1 /迭代查询返回的行。 For each of this lines, check if the post involved in this line exists in the dictionary. 对于每一行,检查字典中是否存在此行中涉及的帖子。 No -> Add a new post object. 否 - >添加新的帖子对象。 Yes -> Just add the comment to the existing post object. 是 - >只需将注释添加到现有的帖子对象即可。

2/ Iterate through your dictionary to add each post contained in it to an array. 2 /迭代你的字典,将其中包含的每个帖子添加到一个数组中。

3/ Sort your array by the id of the post (here i'm assuming that the id is in the same order as the posts, but just a little advice: you should probably have a post date and sort by post date). 3 /按照帖子的ID对数组进行排序(这里我假设id与帖子的顺序相同,但只是一些建议:你应该有一个发布日期并按发布日期排序)。

If you master PHP syntax, your should be able to implement it easily. 如果您掌握了PHP语法,那么您应该能够轻松实现它。 Don't hesitate to submit an edit if you know the PHP syntax for this. 如果你知道PHP的语法,请不要犹豫提交编辑。

I hope this helps. 我希望这有帮助。

This code 这段代码

    foreach($query->result() as $row){
      // if the post hasn't been created in the array
      // create it
        if(!isset($post[$row->post_id])){
            $post[$row->post_id] = array(
              "post_id" => $row->post_id,
              "post_text" => $row->post_text
            );
        }
        // if a comment is found
        if(isset($row->comment_id)){
            $post[$row->post_id]['comments'][] = array(
              "comment_id" => $row->comment_id,
              "comment_text" => $row->comment_text
            );
        }
    }

    return $posts[] = array_values($post);

returns this (what I need): 返回此(我需要的):

   [
     {
       "post_id"   : "something",
       "post_text" : "something else"
     },
     {
       "post_id"   : "something",
       "post_text" : "something else",
       "comments" : [
         {"comment_id":1,"comment_text":"something"},
         {"comment_id":2,"comment_text":"something"}
       ]
     },
    ....
   ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM