我有一个 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()
。
关于php - 将多个 JSON 对象合并为一个对象并将不相等的数据作为数组添加到该对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32531550/