我想使用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){...}
答案 0 :(得分:6)
ksort适用于数组,而不是字符串:
$array = json_decode($json, true);
ksort($array);
echo json_encode($array);
答案 1 :(得分:1)
为了使用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。
答案 2 :(得分:0)
这样:
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中您有已排序的数据