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?

1
  • Build the php-array differently. Instead of having 10=>"apple" make it array(1=> array(10 => "apple),...). Then handle the output in the frontend. Commented Aug 16, 2013 at 12:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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"}
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.