PHP根据json中的一个键值排序的
程序员文章站
2022-03-11 17:04:02
...
{
"data":[
{"roleId":"qai41","role":"qai43","level":"45","sex":"0"},
{"roleId":"qai41","role":"qai41","level":"78","sex":"0"},
{"roleId":"qai41","role":"qai42","level":"44","sex":"0"}
]
}
怎么取出level最大的role?
回复内容:
{
"data":[
{"roleId":"qai41","role":"qai43","level":"45","sex":"0"},
{"roleId":"qai41","role":"qai41","level":"78","sex":"0"},
{"roleId":"qai41","role":"qai42","level":"44","sex":"0"}
]
}
怎么取出level最大的role?
$arr = {
"data":[
{"roleId":"qai41","role":"qai43","level":"45","sex":"0"},
{"roleId":"qai41","role":"qai41","level":"78","sex":"0"},
{"roleId":"qai41","role":"qai42","level":"44","sex":"0"}
]
};
$cache = 0;
$role = '';
for($i=0;$i $cache){
$cache = $arr['data'][$i]['level'];
$role = $arr['data'][$i]['role'];
}
}
最后读取$role就可以了
$t = json_decode('{
"data":[
{"roleId":"qai41","role":"qai43","level":"45","sex":"0"},
{"roleId":"qai41","role":"qai41","level":"78","sex":"0"},
{"roleId":"qai41","role":"qai42","level":"44","sex":"0"}
]
}', true);
function levelSort($a, $b) {
if($a['level'] == $b['level']) return 0;
return ($a['level']
$str = '{
"data":[
{"roleId":"qai41","role":"qai43","level":"45","sex":"0"},
{"roleId":"qai41","role":"qai41","level":"78","sex":"0"},
{"roleId":"qai41","role":"qai42","level":"44","sex":"0"}
]
}';
$arr = json_decode($str);
foreach ($arr->data as $k => $v) {
$t[$v->level] = $v->role;//level做键,role做值
}
krsort($t);//按键逆序排序
$t = array_merge($t);//让键0打头
var_dump($t[0]);//第一个即最大的level的role
上一篇: Vue在前端开发中需要注意什么
下一篇: phpmyadmin导出木马的四种方法
推荐阅读
-
php each 返回数组中当前的键值对并将数组指针向前移动一步实例_php实例
-
PHP中SERIALIZE和JSON序列化与反序列化的区别
-
PHP 多维数组的排序问题 根据二维数组中某个项排序_php技巧
-
javascript中的变量如何传到php中,一个高难问题 100大分!
-
在js中取json.php的数据并赋值给js中变量
-
php中如何从一个文件获取另一个php文件的代码?(而不是执行结果)
-
JSON在PHP中的应用
-
php在多维数组中根据键名快速查询其父键以及父键值的代码_PHP教程
-
php中的一些数组排序方法分享_PHP
-
php在多维数组中根据键名快速查询其父键以及父键值的代码_php技巧