将多个JSON对象合并为单个对象,并将不相等的数据作为数组添加到此对象中

时间:2015-09-11 20:22:05

标签: php mysql json laravel

我有一个Laravel联接数据库查询,它返回给我:

[
  {
    "post_id": 28,
    "site_id": 16,
    "url": "http://something.com",
    "title": "Website title",
    "post_created_at": "2015-07-06 02:40:01",
    "post_updated_at": "2015-09-08 22:33:20",
    "tag_map_id": 11,
    "tag_id": 9,
    "tag_name": "dog"
  },
  {
    "post_id": 28,
    "site_id": 16,
    "url": "http://something.com",
    "title": "Website title",
    "post_created_at": "2015-07-06 02:40:01",
    "post_updated_at": "2015-09-08 22:33:20",
    "tag_map_id": 12,
    "tag_id": 10,
    "tag_name": "cat"
  }
]

因此,同一个post_id可以有多个结果,但是一个帖子也可以有多个标签。

我想要的是将这些多个结果合并到一个JSON对象中,该对象包含数组中所有与标记相关的内容。所以每个post_id应该只有一个JSON对象。如下例所示:

[
  {
    "post_id": 28,
    "site_id": 16,
    "url": "http://something.com",
    "title": "Website title",
    "post_created_at": "2015-07-06 02:40:01",
    "post_updated_at": "2015-09-08 22:33:20",
    "tag_map_id": [11, 12],
    "tag_id": [9, 10],
    "tag_name": ["dog", "cat"]
  }
]

如何在PHP中实现这种合并?

1 个答案:

答案 0 :(得分:0)

我根本不会使用join。我会用Eloquent,

Post::with('tags')

然后在生成的Collection上使用json_encode()