Prevent json_encode associative array sorting [duplicate]

风格不统一 提交于 2019-11-27 06:48:05

问题


This question already has an answer here:

  • json_encode not preserving order 2 answers

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?


回答1:


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>



回答2:


Try this:

    $ar = array();
    $ar[1] = array('1'=>'one');
    $ar[2] = array('2'=>'two');
    $ar[3] = array('3'=>'three');
    print_r($ar);
    $str= json_encode($ar);
    print_r($str);

it should work, at-least helps me !



来源:https://stackoverflow.com/questions/21216391/prevent-json-encode-associative-array-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!