5

When I try to do asort($data) and then return it like response()->json($data, 200), the output is still in its original position.

Here's the code:

$fruits = array( 'guava', 'apple', 'orange' );
asort( $fruits );
return response()->json( $fruits, 200 );

then the output is still in its position.

{
  0: "guava",
  1: "apple",
  2: "orange"
}

But when I try to dump the data just after the sorting happen, like

$fruits = array( 'guava', 'apple', 'orange' );
asort( $fruits );
dd( $fruits );

I'm getting the right position of data.

array:3 [
  1 => "apple"
  0 => "guava"
  2 => "orange"
]

Any idea, why this happen? and how can I solve this? Im using Laravel 5.1

4
  • Have you tried return response()->json( $fruits ); without the status 200? Commented Jul 14, 2015 at 11:48
  • Yes, its still doesn't work. Commented Jul 14, 2015 at 11:49
  • if everything fails try return json_encode( $fruits); Commented Jul 14, 2015 at 12:02
  • @pinkalvansia, that is exactly the same thing. Commented Jul 14, 2015 at 12:03

2 Answers 2

3

The fact that you can have an array with numerical index out of order in php is purely a php thing.

The json output shouldn't care about that.. it's possible that json_encode is called on the fly, or that what you're seeing is simply an optimisation from the browser (it is an object {}).

See this SO question that has some valuable input regarding this: Prevent json_encode associative array sorting.

However in your context, unless you really care about the index, asort is probably not what you want. You want sort.

Edit if you want to maintain both order and key assoc, you need to change the structure to an array of object {key,value}

Edit 2 you can reduce your array to that structure like this (php 5.4+):

$fruits = array_map(function($index,$value) {
        return ['index'=>$index,'value'=>$value];
    },array_keys($fruits),$fruits);
Sign up to request clarification or add additional context in comments.

3 Comments

I need "asort()" because I need to "maintain key association".
Yes, you're right but that's a different structure.
@kjames. Yes, that's correct. What you're trying to do is only applicable in php, not json. You'll need to adapt.
0

After thinking about it, the problem is that your JSON response will sort the array by keys. Since you maintain index association with asort(), that array isn't really sorted according to JSON. Use sort() instead.

http://php.net/manual/en/function.sort.php

1 Comment

Okay, but I need to "maintain key association" that's why I cannot use "sort()".

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.