search

Home  >  Q&A  >  body text

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

{
    "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?

ringa_leeringa_lee2915 days ago647

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-10 14:59:19

    $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
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:59:19

    $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<3;$i++){
        if($arr['data'][$i]['level'] > $cache){
            $cache = $arr['data'][$i]['level'];
            $role = $arr['data'][$i]['role'];
        }
    }
    最后读取$role就可以了
    

    reply
    0
  • 阿神

    阿神2017-04-10 14:59:19

    $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']<$b['level']) ? 1 : -1;
    }
    
    usort($t['data'], 'levelSort');
    print_r($t['data'][0]['roleId']);
    

    reply
    0
  • Cancelreply