通过数组JavaScript作为数组不是从PHP JSON

问题描述:

首先,这不是一个重复的问题。我已经通过了一些类似的问题看,大部分的回答是,我使用的是现在。

First this is not a duplicate questions. I've looked through some similar problem and most of the answer is what I am using right now.

这是问题所在成立,
在PHP端

Here is the problem set up, on PHP side

$array = array('name' => 'a', 'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20));
echo json_encode($array);

在JS端

数据= $ .parseJSON(数据); //数据是从PHP脚本返回
  上述

data = $.parseJSON(data); // data is the return from the php script above

正如你可以看到$数组['数据']是一个关联数组与数字号码作为其关键和排序。在解析成JSON,JavaScript的改变数组的顺序和分类0和1的数字键,并把他们的对象的头部。

As you can see the $array['data'] is an associative array with numeric number as its key and sorted in order. While parsing into JSON, javascript altered the order of that array and sorted 0 and 1 as numeric key and put them to the head of the object.

我知道这对某些浏览器,如Chrome和IE9标准行为。
我读过的地方,人们建议用数组坚持严格,如果我要保持数组的顺序。
但我的问题是你如何从PHP反馈数组JavaScript作为一个数组,而不是使用JSON对象?还是有其他的解决这类问题。感谢事先输入。

I know this is standard behavior for certain browser such as chrome, and IE9. I've read somewhere that people suggest stick with array strictly if I want to maintain the order of the array. But my question is how do you feed back an array from PHP to javascript as an array instead of using json object? Or is there other solution to this kind of problem . Thanks for the input in advance.

感谢您的输入提前

使用数组来维持秩序,再一个对象来创建地图。有两种方法。我建议:

Use an array to maintain order, and then an object to create the map. There are two ways. I would suggest:

$array = array('name' => 'a', 'data' => 
  array(
    array('key' => 0, 'value' => 15),
    array('key' => 0.25, 'value' => 18),
    array('key' => 0.35, 'value' => 19),
    array('key' => 1, 'value' => 20),
  )
);
echo json_encode($array);

这将给你的JSON:

Which will give you the JSON:

{
    "name": "a",
    "data": [
       {"key": 0, "value": 15},
       {"key": 0.25, "value": 18},
       {"key": 0.35, "value": 19},
       {"key": 1, "value": 20}
    ]
}

然后,你将有订单,但查找某个键将更加困难。如果你想这是很容易,你可以返回一个映射对象,以及这样的:

Then you will have order but to look up a certain key will be more difficult. If you want that to be easy you can return a mapping object as well like this:

$array = array('name' => 'a', 'data' => 
  array(
    "0" => 15,
    "0.25" => 18,
    "0.35" => 19,
    "1" => 20,
  ),
  'order' => array("0", "0.25", "0.35", "1")
);
echo json_encode($array);

这将给你:

{
    "name": "a",
    "data": {
       "0": 15,
       "0.25": 18,
       "0.35": 19,
       "1": 20
    },
    "order": ["0", "0.25", "0.35", "1"]
}

一回你的数据应该被证明是最有用的为您的特定用例的这两种方法。

One of these two methods of returning your data should prove to be the most useful for your specific use case.