PHP对已解码的json文件进行排序

时间:2016-12-20 14:31:31

标签: php json sorting

我使用json_decode()将JSON文件解码为$data。所以我想现在我有一个数组数组:

$data:
1 first= "bob", last= "smith", middle= "t", ID= "123"
2 first= "paul", last= "adams", middle= "d", ID= "38"
3 first= "jon", last= "williams", middle= "g", ID= "132"

我想最后排序$data。我想我需要使用usort(),但无法让它发挥作用。

1 个答案:

答案 0 :(得分:1)

试试这个:

$data = [
    ['first' => 'bob', 'last' => 'smith', 'middle' => 't', 'ID' => '123'],
    ['first' => 'paul', 'last' => 'adams', 'middle' => 'd', 'ID' => '38'],
    ['first' => 'jon', 'last' => 'williams', 'middle' => 'g', 'ID' => '132'],
];

usort($data, function ($string1, $string2) {
    return strcmp($string1['last'], $string2['last']);
});

输出:

Array
(
    [0] => Array
        (
            [first] => paul
            [last] => adams
            [middle] => d
            [ID] => 38
        )

    [1] => Array
        (
            [first] => bob
            [last] => smith
            [middle] => t
            [ID] => 123
        )

    [2] => Array
        (
            [first] => jon
            [last] => williams
            [middle] => g
            [ID] => 132
        )

)