【问题标题】:Laravel JSON to ArrayLaravel JSON 到数组
【发布时间】:2021-04-12 00:17:22
【问题描述】:

我必须将 json 转换为来自 laravel 通知表 data 字段的 arry,

这是dd($user->notifications);上显示的数据

这是响应在邮递员中显示的方式

我需要在[] 中显示有效载荷,如下所示

 {
    "payload": [ {
        "title": "PHP Developer Accepted",
        "description": "<p>This is a professional IT Job&nbsp;</p>",
        "user_id": 54,
        "job_id": "01"
    }],
    "message": "",
    "result": true
}

这是我的控制器索引函数

protected function index()
{
    $user = DeviceAuthenticator::getUserByAccessToken();

    foreach ($user->notifications as $notification) {
        $notifications = $notification->data;
    }

    return response()->apiSuccess($notifications); 
}

但在我在响应之前转储 $notifications 之前,它显示为一个数组

dd($notifications);

【问题讨论】:

    标签: php arrays json laravel jsondecoder


    【解决方案1】:

    只需将[] 包装在您的变量中,就像

    protected function index()
    {
        $user = DeviceAuthenticator::getUserByAccessToken();
    
        foreach ($user->notifications as $notification) {
            $notifications = $notification->data;
        }
    
        return response()->apiSuccess([$notifications]);  // wrap in array
    }
    
    

    你可能需要这样的东西

    protected function index()
    {
        $user = DeviceAuthenticator::getUserByAccessToken();
    
        $notifications = [];
        foreach ($user->notifications as $notification) {
            $notifications[] = $notification->data;
        }
    
        return response()->apiSuccess($notifications);
    }
    

    这里notifications是一个数组

    【讨论】:

      【解决方案2】:

      你可以试试添加这个
      ->toArray();

      【讨论】:

        猜你喜欢
        • 2022-01-08
        • 2021-04-14
        • 2017-04-10
        • 2021-03-20
        • 2018-08-05
        • 2014-03-09
        • 2015-03-15
        • 2015-04-15
        • 2021-01-26
        相关资源
        最近更新 更多