PHP:
$arr[0] = 'A';
$arr['C'] = 'C';
$arr[10] = 'B';
echo json_encode($arr);
JQuery:
$.each(result, function(i, item) {
console.log(i + " => " + item);
});
期望的输出:
0 => A
C => C
10 => B
相反,我得到:
0 => A
10 => B
C => C
如何防止它在不修改 PHP 代码或重组数组的情况下重新排序我的数组?
编辑:
当使用 firebug 在响应 header 中调用 ajax 时,它的顺序似乎是正确的:
"0":"A","C":"C","10":"B"
但是,当我在 $.each 循环中执行 console.log 时,它会重新排序
最佳答案
您的 $arr
是一个对象,而不是数组,并且键没有索引或排序。
在 JavaScript 中,您无法保证对象属性的迭代顺序,只能保证数组的索引键(即整数键)。
要迭代普通对象,$.each
使用标准 for..in
构造,其中 the MDN precises that
A for...in loop iterates over the properties of an object in an arbitrary order
如果你想保持任意键值有序,你应该将它们存储在适当的数组中:
var arr = [];
arr.push({key:0, value:'A'});
arr.push({key:'C', value:'C'});
arr.push({key:10, value:'B'});
关于php - 使用 PHP 中的 json_encode 时,JQuery $.each 循环会重新排序我的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16154427/