I have a function return an associate numeric key array:
public static function getSortedFruits()
{
$fruits = array('100' => 'lemon', '102' => 'orange', '103' => 'apple', '204' => 'banana');
asort($fruits);
print_r($fruits); // return sorted array('103' => 'apple', '204' => 'banana', '100' => 'lemon', '102' => 'orange')
return $fruits;
}
i call this function from PHP code, the array is sorted
$fruits = getSortedFruits(); // sorted array
when I call this function from ajax, the array is the same as before, isn't sorted
$('#fruits').bind('change', function() {
$.ajax({
type: 'POST',
url: '/ajax/getFruits', // route to getFruits function
dataType: 'json',
success: function(result) {
console.log(result); // the array isn't sorted
});
});
If the key of the $fruits is not numeric, such as a, b, c, the result is sorted as normally both function call and ajax request.
asort method sorts based on array values. There is no difference in order from outputs from print_r and json_encode.
$fruits = array('1' => 'lemon', '2' => 'orange', '3' => 'apple', '4' => 'banana');
asort($fruits);
print_r($fruits);
// Above outputs:Array ( [3] => apple [4] => banana [1] => lemon [2] => orange )
echo json_encode($fruits);
// Above outputs: {"3":"apple","4":"banana","1":"lemon","2":"orange"}
I have tested your code on my local pc with xampp, you will have to use
print_r($fruits)
Or
echo json_encode($fruits);
Instead of
return $fruits
UPDATED
encode the array after returned function getSortedFruits()
, something like
$fruits = getSortedFruits(); // sorted array
json_encode($fruits)