PHP:
$arr[0] = 'A';
$arr['C'] = 'C';
$arr[10] = 'B';
echo json_encode($arr);
JQuery:
$.each(result, function(i, item) {
console.log(i + " => " + item);
});
Desired Output:
0 => A
C => C
10 => B
Instead I Get:
0 => A
10 => B
C => C
how can i prevent it to re-order my array without modifying the PHP code or restructuring the array?
Edit:
when ajax is called in response headers using firebug it seems to be in correct order:
"0":"A","C":"C","10":"B"
however when I do console.log inside $.each loop its re-ordered
Your $arr
is an object, not an array and the keys aren't indexed nor ordered.
You don't have guarantee in JavaScript about the iteration order on object properties, only the indexed keys (i.e. integer keys) of arrays.
To iterate over a plain object, $.each
uses the standard for..in
construct on which the MDN precises that
A for...in loop iterates over the properties of an object in an arbitrary order
If you want to keep arbitrary key-value ordered, you should store both in a proper array :
var arr = [];
arr.push({key:0, value:'A'});
arr.push({key:'C', value:'C'});
arr.push({key:10, value:'B'});