Laravel JSON 到数组

Laravel JSON to Array

我必须将 json 转换为 laravel 通知 table data 字段,

这是 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 before response 之前它显示为一个数组

dd($notifications);

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

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是一个数组

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