How to properly fix - Cannot use empty array elements in arrays I have the code below but it showing an error "Cannot use empty array elements in arrays".
It seems that the issue is in this line }), collect(json_decode($post['comments'], true))->map(function ($comment) {
Code:
'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'],
];
}),,
]
Do you want to merge those two collections into one? Because you don't use a key for the second collection.. so maybe this will work:
'comments' => collect(json_decode($configs['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
})->merge(collect(json_decode($posts['comments'], true))->map(function ($comment) {
return [
'title' => $comment['attributes']['title'],
'message' => $comment['attributes']['message'],
];
})),
@Nakov Thanks! Like that it shows "json_decode(): Argument #1 ($json) must be of type string, array given
". Do you know why?
@bernardev The answer is in the error: must be of type string, array given
so either your $configs['comments'] is already an array so you don't need to use json_decode just pass them to the collect method, or your $posts['comments'] is an array.
@Nakov Thanks, its strange because like that it shows "Cannot access offset of type string on string
".
dd($post['comments']);
^ array:1 [▼
0 => array:3 [▶]
]
dd($config['comments'] has this format "^ "[{"key": "o0Gdz1EsxOpOLN", "layout": "comment", "attributes": {"title": "a", "comment": "b"}}]" "
@bernardev so for $config['comments'] you need to use json_decode and for $post['comments'] I don't know how you are constructing that, but it is an array of arrays for some reason. So you either just get the first array, or work out on having just single array..
Maybe:
collect($post['comments'])->values()->map...
Please sign in or create an account to participate in this conversation.