防止 json_encode 关联数组排序 [英] Prevent json_encode associative array sorting

查看:48
本文介绍了防止 json_encode 关联数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关联数组

数组([289] =>大批('名称'=>'一'),[292] =>大批('名称'=>'一'),[290] =>大批('名称'=>'一'))

在我对这个数组使用 json_encode 之后.键已排序,尽管我将其作为 JSON 对象获取.

有没有办法防止这种行为?

解决方案

没有标准规定它必须按特定顺序排列.

查看相关问题:如何阻止 Chrome 和 Opera 按索引 ASC 对 JSON 对象进行排序?

注意:我们说的是一个 PHP 函数,但结果基本上是 javascript,所以关于不存在的标准的声明也适用.

顺便说一句:我已经使用以下代码对其进行了测试.PHP 本身似乎不会对数组进行排序,firefox 也不会(根据 firebug 控制台).

<?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);?>

<脚本>var foo = <?=$string?>;控制台日志(富);

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?

解决方案

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>

这篇关于防止 json_encode 关联数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆