4

1

In PHP:

$arr = array( 10=>"ten", 5=>"five", 2=>"two"); return json_encode($arr);

In JS - $.ajax():

success: function(data){ console.log(data);}

2

What I see in console is :

Object {2: "two", 5: "five", 10: "ten"},

I want to use for(var i=0; i< data.length,i++) but failed.

Finally it works in this way : for(var i in data)

3

My Question: Why the array is sorted? I want the array to keep unsorted.

Anyone helps me?

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
yip
  • 123
  • 1
  • 11
  • This might help http://stackoverflow.com/q/6551949/3639582 – Shaunak D Apr 13 '15 at 11:48
  • 1
    They are sorted because you're assigning certain values to an integer-indexed array, i.e. the following: `[0: null, 1: null, ... 5: "five"]` etc – Jack Apr 13 '15 at 11:49
  • Check [this](http://stackoverflow.com/questions/21216391/prevent-json-encode-associative-array-sorting) post – anpsmn Apr 13 '15 at 11:58

1 Answers1

2

JSON cannot represent a sparse array, which is what your data would be if it did.
So you get an object instead of an array and the is no standard that says object properties has to sorted in any specific way or not sorted at all.
You can try having your data in 2 arrays

$arr = array( 'indecies'=>array(10,5,2), 'values'=>array("ten","five","two") ); 
return json_encode($arr);
for(var i=0; i< data.indecies.length,i++){
    // do something with
    //data.indecies[i]
    //data.values[i]
}
Musa
  • 96,336
  • 17
  • 118
  • 137