我有一个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中实现合并?
我根本不会使用join
。我会用Eloquent,
Post::with('tags')
,然后对生成的Collection使用json_encode()