0

I have an array with this structure:

[
    {
        "id": "2644688"
    },
    {
        "id": "2644689"
    }
]

I'm trying to reverse it using array_reverse:

$reversed = array_reverse($result, true);
return $response->withJson($reversed);

but I get:

{
 "0": {
       "id": "2644688"
 },
 "1": {
       "id": "2644689"
 }
}

the order is the same, the function array_reverse just added the numerical indexes, I did something wrong?

Charanoglu
  • 969
  • 1
  • 6
  • 23

2 Answers2

1

You should not pass true in the second argument of array_reverse.

Try replacing your code to:

$reversed = array_reverse($result, false);

Or just:

$reversed = array_reverse($result);

The second argument is preserving original array keys. The problem with that is that JavaScript will change it's order according to the keys, so the output of the json will be:

{"1":{"id":"2644689"},"0":{"id":"2644688"}}

And JavaScript will change the order to 0,1.

HTMHell
  • 4,572
  • 4
  • 30
  • 70
1

According to array_reverse documentation. Second parameter, if set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.

So try removing true as second parameter.

$reversed = array_reverse($result);
return $response->withJson($reversed);
Lovepreet Singh
  • 4,404
  • 1
  • 12
  • 34