PHP:按键对JSON数据排序

PHP:按键对JSON数据排序,php,json,sorting,Php,Json,Sorting,我想使用PHP按字母顺序对一行JSON数据进行排序。因此,最后: {"one":"morning","two":"afternoon","three":"evening","four":"night"} 变成: {"four":"night","one":"morning","three":"evening","two":"afternoon"} 我尝试过使用ksort但没有效果: $icons = json_decode(file_get_contents("icons.json"));

我想使用PHP按字母顺序对一行JSON数据进行排序。因此,最后:

{"one":"morning","two":"afternoon","three":"evening","four":"night"}
变成:

{"four":"night","one":"morning","three":"evening","two":"afternoon"}
我尝试过使用
ksort
但没有效果:

$icons = json_decode(file_get_contents("icons.json"));
ksort($icons);
foreach($icons as $icon => $code){...}

ksort使用数组,而不是字符串:

$array = json_decode($json, true);
ksort($array);
echo json_encode($array);  

要使用
ksort
,首先必须使用以下命令将json转换为PHP数组:

// the true argument specifies that it needs to be converted into a PHP array
$array = json_encode($your_json, true);
然后应用于该数组


最后,
json\u再次对其进行编码,以将结果返回到json中。

这里这样:

var dataArr = [];
for (value in oldData) {
    var tmp = oldData[key];
    dataArr.push(parseInt(key)tmp});
}

dataArr.sort(function(a, b){
    if (a.word < b.word) return -1;
    if (b.word < a.word) return 1;
    return 0;
});
var-dataArr=[];
用于(旧数据中的值){
var tmp=旧数据[键];
dataArr.push(parseInt(key)tmp});
}
数据数组排序(函数(a,b){
if(a.word

现在在dataArr中,您有了已排序的数据

您可以发布您使用的PHP代码吗?您是否先调用了
json\u decode()
$arr=json\u decode($yourJSONString);k港口(arr)
您是否对数组进行了var_转储以查看它是否被正确读取?完美;需要添加“true”!干杯,伙计们!如果这解决了你的问题,你可以接受答案@deceze,这些点应该给你:-)这个方法可以用于嵌套数据吗?也就是说,按其键对每一层嵌套进行排序?
var dataArr = [];
for (value in oldData) {
    var tmp = oldData[key];
    dataArr.push(parseInt(key)tmp});
}

dataArr.sort(function(a, b){
    if (a.word < b.word) return -1;
    if (b.word < a.word) return 1;
    return 0;
});