如何正确修复 - 不能在数组中使用空数组元素

How to properly fix - Cannot use empty array elements in arrays

我有下面的代码,但它显示错误“不能在数组中使用空数组元素”。

看来问题出在这一行}), collect(json_decode($post['comments'], true))->map(function ($comment) {

代码:

'data' => [
    'comments' =>
    collect(json_decode($configs['comments'], true))->map(function ($comment) {
        return [
            'title' => $comment['attributes']['title'],
            'message' => $comment['attributes']['message'],
        ];
    }),  collect(json_decode($posts['comments'], true))->map(function ($comment) {
        return [
            'title' => $comment['attributes']['title'],
            'message' => $comment['attributes']['message'],
        ];
    }),
]

如果我们简化您的代码,它看起来像这样;

'data' => [
    'comments' =>
       collect(),  
       collect()
]

这不是一个有效的语法。你可以这样试试;

$comments = collect(json_decode($configs['comments'], true))->map(function ($comment) {
    return [
        'title' => $comment['attributes']['title'],
        'message' => $comment['attributes']['message'],
    ];
});
$postComments =  collect(json_decode($posts['comments'], true))->map(function ($comment) {
    return [
        'title' => $comment['attributes']['title'],
        'message' => $comment['attributes']['message'],
    ];
});

'data' => [
    'comments' => $comments->merge($postComments)->toArray()
];