3 回答
TA贡献1877条经验 获得超6个赞
JSON_ENCODE 在 PHP 中保留了键顺序,但在 Javascript 中并非如此。
在PHP:
$arr = [3 => "A", 1 => "B", 2 => "C"];
echo json_encode($arr);
Output:
{"3":"A","1":"B","2":"C"}
但是如果你尝试同样的 Javascript
var obj = {"3":"A","1":"B","2":"C"};
console.log(JSON.stringify(obj));
Output:
"{"1":"B","2":"C","3":"A"}"
要在 javascript 中也保留键顺序,您需要在 PHP 中创建对象数组。
$newArr = [];
foreach($arr as $key => $value){
$newArr[] = [$key => $value];
}
echo json_encode($newArr);
Output:
[{"3":"A"},{"1":"B"},{"2":"C"}]
现在您可以在 Javascript 中访问相同的内容。
arrObj = JSON.parse(str);
arrObj.forEach(function(element) {
for (strKey in element) {
console.log(strKey + ' : ' + element[strKey]);
}
});
Output:
3 : A
1 : B
2 : C
TA贡献1776条经验 获得超12个赞
您可以使用该JSON_FORCE_OBJECT参数使json_encode输出成为对象。这将在输出中包含 javascript 识别的键:
echo json_encode(array_values($new), JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES);
输出:
{
"71": "07/09/2019-Saturday",
"81": "08/09/2019-Sunday",
"83": "09/09/2019-Monday",
"84": "10/09/2019-Tuesday",
"72": "15/09/2019-Sunday",
"73": "16/09/2019-Monday",
"74": "17/09/2019-Tuesday",
"75": "18/09/2019-Wednesday"
}
3v4l.org 上的演示
在 JavaScript 中:
let json = '{\
"71": "07/09/2019-Saturday",\
"81": "08/09/2019-Sunday",\
"83": "09/09/2019-Monday",\
"84": "10/09/2019-Tuesday",\
"72": "15/09/2019-Sunday",\
"73": "16/09/2019-Monday",\
"74": "17/09/2019-Tuesday",\
"75": "18/09/2019-Wednesday"\
}';
let obj = JSON.parse(json);
console.log(obj[72]);
- 3 回答
- 0 关注
- 151 浏览
添加回答
举报