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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With