1

I have an array like this

Array
(
    [0] => Array
        (
            [title] => first 
            [description] => first item
        )

    [1] => Array
        (
            [title] => second 
            [description] => second item
        )

)

And remove an item from the array using collection forget() method

$new = collect($arr);
$new->forget(0);
echo json_encode($new->all());

Here is the json output of the above

{"1":{"title":"second ","description":"second item"}}

But i am expecting a json like this

[{"title":"second ","description":"second item"}]

Also how can i re index the above array after applying forget() method??

0

1 Answer 1

1

Start Array

Array
(
    [0] => Array
        (
            [title] => first 
            [description] => first item
        )

    [1] => Array
        (
            [title] => second 
            [description] => second item
        )

)

You remove the first element of the array:

Array
(
    [1] => Array
        (
            [title] => second 
            [description] => second item
        )

)

json_encode on this array, returns this:
{"1":{"title":"second ","description":"second item"}}

So the output that you have, is correct.

You need to run json_encode on this array, for the output that you want:

Array
(
    [title] => second 
    [description] => second item
)

You can use, for example, the array_shift function for this:

$new = collect($arr);
$new->forget(0);
echo json_encode(array_shift($new->all()));

Another example is the array_values function, in case you want more than one array:

$new = collect($arr);
$new->forget(0);
echo json_encode(array_values($new->all()));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.