Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent json_encode associative array sorting [duplicate]

I have a associative array

Array(
   [289] => Array(
    'name'=> 'One'
   ),
   [292] => Array(
    'name'=> 'One'
   ),
   [290] => Array(
    'name'=> 'One'
   )
)

After i use json_encode on this array. The keys are sorted, although i get it as JSON object.

Is there way to prevent this behaviour?

like image 537
rbawaskar Avatar asked Jan 19 '14 11:01

rbawaskar


1 Answers

there is no standard that says it has to be in a certain order.

See this for a related question: How do you stop Chrome and Opera sorting JSON objects by Index ASC?

note: we're talking about a PHP function, but the result is basically javascript, so the statement about the non-existing standard applies as well.

btw: I have tested it with the following code. PHP itself doesnt seem to sort the array, firefox doesn't as well (according to the firebug console).

<pre>
<?php
    $array = array();
    $array[289] = array('name'=>'One');
    $array[292] = array('name'=>'One');
    $array[290] = array('name'=>'One');
    print_r($array);
    $string = json_encode($array);
    print_r($string);
?>
</pre>
<script>
    var foo = <?=$string?>;
    console.log(foo);
</script>
like image 184
Zim84 Avatar answered Oct 19 '22 07:10

Zim84