doubu1970 2015-09-11 20:22
浏览 348

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

I have a Laravel join database query which returns me this:

[
  {
    "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"
  }
]

So there can be multiple results with same post_id but one post can also have multiple tags.

What I want, is to merge these multiple results into one JSON object which contains all the tag-related stuff in array. So there should be only one JSON-object per one post_id. Like the example below:

[
  {
    "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"]
  }
]

How can I achieve this merging in PHP?

  • 写回答

1条回答 默认 最新

  • dongyongyin5339 2015-09-11 20:57
    关注

    I wouldn't use join at all. I would use Eloquent,

    Post::with('tags')

    and then use json_encode() on the resulting Collection.

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)