PHP根据json中的一个键值排序的

WBOY
Lepaskan: 2016-06-06 20:43:25
asal
2429 orang telah melayarinya

<code class="lang-php">{
    "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"}

          ]
}
</code>
Salin selepas log masuk
Salin selepas log masuk

怎么取出level最大的role?

回复内容:

<code class="lang-php">{
    "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"}

          ]
}
</code>
Salin selepas log masuk
Salin selepas log masuk

怎么取出level最大的role?

<code>$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就可以了
</code>
Salin selepas log masuk

<code>$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']</code>
Salin selepas log masuk

<code>$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
</code>
Salin selepas log masuk
Label berkaitan:
php
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan