我有一个函数返回一个关联的数字键数组:
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;
}
我从PHP代码调用此函数,数组已排序
$fruits = getSortedFruits(); // sorted array
当我从ajax调用这个函数时,数组和以前一样,没有排序
$('#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
});
});
如果$ fruits的键不是数字,例如a,b,c,则结果通常按函数调用和ajax请求排序。
答案 0 :(得分:1)
asort 方法根据数组值进行排序。 print_r和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"}
答案 1 :(得分:0)
我已经使用xampp在我的本地电脑上测试了您的代码,您将不得不使用
print_r($fruits)
或强>
echo json_encode($fruits);
而不是
return $fruits
<强>已更新强>
在返回函数getSortedFruits()
之后对数组进行编码,类似于
$fruits = getSortedFruits(); // sorted array
json_encode($fruits)