一尘不染

按键值对PHP中的JSON对象进行排序

json

我需要通过PHP脚本中的“得分”值对此类信息进行排序,该怎么办?:

Array
(
 [0] => stdClass Object
    (
        [name] => Morts par Déshydratation
        [score] => 4
        [id] => dwater
    )

 [1] => stdClass Object
    (
        [name] => Réparations de chantiers
        [score] => 87
        [id] => brep
    )

 [2] => stdClass Object
    (
        [name] => Campeur téméraire
        [score] => 77
        [id] => camp
    )

 [3] => stdClass Object
    (
        [name] => Décoration
        [score] => 112
        [id] => deco
    )
)

PS:这已经在PHP值中,我已经使用了json_decode。*


阅读 450

收藏
2020-07-27

共1个答案

一尘不染

$data这个样子的:

Array
(
    [0] => stdClass Object
        (
            [name] => Morts par Déshydratation
            [score] => 4
            [id] => dwater
        )

    [1] => stdClass Object
        (
            [name] => Réparations de chantiers
            [score] => 87
            [id] => brep
        )

    [.] => ....
)

您可以usort()用来对数组进行排序:

<?php                                                                                                                                                                                                       
usort($data, function($a, $b) { //Sort the array using a user defined function
    return $a->score > $b->score ? -1 : 1; //Compare the scores
});

print_r($data);   
?>

输出:

Array
(
    [0] => stdClass Object
        (
            [name] => Décoration
            [score] => 112
            [id] => deco
        )

    [1] => stdClass Object
        (
            [name] => Réparations de chantiers
            [score] => 87
            [id] => brep
        )

    [2] => stdClass Object
        (
            [name] => Campeur téméraire
            [score] => 77
            [id] => camp
        )

    [3] => stdClass Object
        (
            [name] => Drogues
            [score] => 49
            [id] => drug
        )

    [4] => stdClass Object
        (
            [name] => Ouverture de porte
            [score] => 11
            [id] => door
        )

    [5] => stdClass Object
        (
            [name] => Morts par Déshydratation
            [score] => 4
            [id] => dwater
        )

)
2020-07-27