我想使用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);
然后对该数组应用ksort。
最后json_encode
再次得到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;
});
现在在dataArr你有你的排序数据