有人请告诉我如何按<{>升序字母顺序中的"name"
对这种 JSON数组进行排序?
{
"response": {
"game_count": 86,
"games": [
"10": {
"appid": 10,
"name": "Counter-Strike",
"playtime_forever": 7604,
"img_icon_url": "6b0312cda02f5f777efa2f3318c307ff9acafbb5",
"img_logo_url": "af890f848dd606ac2fd4415de3c3f5e7a66fcb9f",
"has_community_visible_stats": true
},
"80": {
"appid": 80,
"name": "Counter-Strike: Condition Zero",
"playtime_forever": 62,
"img_icon_url": "077b050ef3e89cd84e2c5a575d78d53b54058236",
"img_logo_url": "acdb28ba1b4c2fcc526332c1b63fc0f7533f087f"
},
.
.
.
]
}
}
答案 0 :(得分:1)
通过这种方式获得所需的结果。
var json_array = {
"response": {
"game_count": 86,
"games": [
{
"appid": 10,
"name": "Counter-Strike",
"playtime_forever": 7604,
"img_icon_url": "6b0312cda02f5f777efa2f3318c307ff9acafbb5",
"img_logo_url": "af890f848dd606ac2fd4415de3c3f5e7a66fcb9f",
"has_community_visible_stats": true
},
{
"appid": 80,
"name": "Counter-Strike: Condition Zero",
"playtime_forever": 62,
"img_icon_url": "077b050ef3e89cd84e2c5a575d78d53b54058236",
"img_logo_url": "acdb28ba1b4c2fcc526332c1b63fc0f7533f087f"
},
.
.
.
]
}
}
json_array.response.games.sort(sort_by('name', false, function(a){
return a.toUpperCase()
}));
var sort_by = function(a, m, n){
var key = n ?
function(p) {return n(p[a])} :
function(q) {return q[a]};
m = !m ? 1 : -1;
return function (x, y) {
return x = key(x), y = key(y), m * ((x > y) - (y > x));
}
}
答案 1 :(得分:1)
您的问题并未明确您的代码所使用的语言。由于问题上的PHP标记,我认为是PHP。
我的方法($json
是原始JSON):
// decode JSON into an array
$arr = json_decode($json,true);
// usort allows sorting by custom attribute
usort(
$arr['response']['games'],
function($a,$b){ return $a['name'] < $b['name'] ? -1 : 1;}
);
// print and check order
print_r($arr);
// turn it back into JSON
$json = json_encode($arr);
文档:usort
答案 2 :(得分:1)
你可以这样做:
<?php
$json = '{
"response": {
"game_count": 86,
"games": [
{
"appid": 10,
"name": "Counter-Strike",
"playtime_forever": 7604,
"img_icon_url": "6b0312cda02f5f777efa2f3318c307ff9acafbb5",
"img_logo_url": "af890f848dd606ac2fd4415de3c3f5e7a66fcb9f",
"has_community_visible_stats": true
},
{
"appid": 80,
"name": "Counter-Strike: Condition Zero",
"playtime_forever": 62,
"img_icon_url": "077b050ef3e89cd84e2c5a575d78d53b54058236",
"img_logo_url": "acdb28ba1b4c2fcc526332c1b63fc0f7533f087f"
},
{
"appid": 23,
"name": "Art Attack",
"playtime_forever": 76604,
"img_icon_url": "6b0312cda02f5f777efa2f3318c307ff9acafbb5",
"img_logo_url": "af890f848dd606ac2fd4415de3c3f5e7a66fcb9f",
"has_community_visible_stats": true
}
]
}
}';
$arrayConvertedJson = json_decode($json, true);
$games = $arrayConvertedJson['response']['games'];
uasort($games, 'sortArray');
function sortArray($a, $b){
if($a['name'] < $b['name']){
return -1;
}
if($a['name'] > $b['name']){
return 1;
}
return 0;
}
$arrayConvertedJson['response']['games'] = $games;
?>