0

I am having a php array which I am encoding using json_encode as shown below.

PHP Code:

$arr=array(10=>"Apple",1=>"Ball",9=>"Cat",11=>"Dog",15=>"Elephant");
echo json_encode($arr);

The json encoded output maintains the same order as the original array. But when I try to access the json_encode output in javascript, that object's elements are sorted in increasing numerical index:

console log:

[{1="Ball",9="Cat",10="Apple",11="Dog",15="Elephant"}]

I want to retain the same order as the original array. How can this be done?

Chris Wesseling
  • 5,012
  • 2
  • 27
  • 64
Mohamed kazzali
  • 33
  • 1
  • 10
  • Build the php-array differently. Instead of having 10=>"apple" make it array(1=> array(10 => "apple),...). Then handle the output in the frontend. – Jakob Aug 16 '13 at 12:10

2 Answers2

2

You should not rely on key order for javascript objects. See this post for more:

Sort JavaScript object by key

If order is important, you should create an array of objects, where is each object looks like:

{9: "Cat"}

As described in the post I linked to, another option, if you just need to iterate in a specific order, is to keep the structure you have, use Object.keys() to get the keys, then sort them, then iterate over the sorted keys.

Community
  • 1
  • 1
Jonah
  • 14,529
  • 18
  • 76
  • 146
1

Try quoting your indexes (effectively making them Strings):

$arr = array("10" => "Apple", "1" => "Ball", "9" => "Cat", "11" => "Dog", "15" => "Elephant");
echo json_encode($arr);

This will give you an object that should look like

{
    "10": "Apple",
    "1": "Ball",
    "9": "Cat",
    "11": "Dog",
    "15": "Elephant"
}

If you must have an array, you need to construct your PHP array a bit differently:

$arr = array(array(10 => "Apple"), array(1 => "Ball"), array(9 => "Cat"), array(11 => "Dog"), array(15 => "Elephant"));
echo json_encode($arr);

Will output

[
    {"10":"Apple"},
    {"1":"Ball"},
    {"9":"Cat"},
    {"11":"Dog"},
    {"15":"Elephant"}
]
André Dion
  • 19,231
  • 7
  • 52
  • 59