0

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'],
        ];
    }),
]
4
  • can you show me the JSON string that you are decoding? Commented May 6, 2022 at 10:57
  • It has this format "^ "[{"key": "o0Gdz1EsxOpOLN", "layout": "comment", "attributes": {"title": "a", "comment": "b"}}]" ". Commented May 6, 2022 at 11:01
  • 1
    @Bernard if that is the case, both maps attempt to get the message property from the attributes object. In the data you provided, that object uses the property key comment, not message. Commented May 6, 2022 at 13:23
  • 1
    Would be good if OP could add the json string to the question. Commented May 7, 2022 at 12:55

1 Answer 1

1

If we simplify your code it seems like this;

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

It is not a valid syntax. You can try like this;

$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()
];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.