PHP

php二维数组怎么根据某个字段排序

小亿
109
2023-11-10 15:05:02
栏目: 编程语言

可以使用array_multisort()函数来根据某个字段对二维数组进行排序。

假设有以下二维数组:

$users = array(
    array('name' => 'John', 'age' => 25, 'city' => 'New York'),
    array('name' => 'Amy', 'age' => 30, 'city' => 'Los Angeles'),
    array('name' => 'Peter', 'age' => 20, 'city' => 'Chicago')
);

如果要根据age字段对数组进行升序排序,可以使用以下代码:

$ages = array_column($users, 'age'); // 提取所有用户的age字段值
array_multisort($ages, SORT_ASC, $users); // 根据age字段值进行排序

print_r($users);

输出结果为:

Array
(
    [0] => Array
        (
            [name] => Peter
            [age] => 20
            [city] => Chicago
        )

    [1] => Array
        (
            [name] => John
            [age] => 25
            [city] => New York
        )

    [2] => Array
        (
            [name] => Amy
            [age] => 30
            [city] => Los Angeles
        )
)

如果要根据city字段对数组进行降序排序,可以使用以下代码:

$cities = array_column($users, 'city'); // 提取所有用户的city字段值
array_multisort($cities, SORT_DESC, $users); // 根据city字段值进行排序

print_r($users);

输出结果为:

Array
(
    [0] => Array
        (
            [name] => Amy
            [age] => 30
            [city] => Los Angeles
        )

    [1] => Array
        (
            [name] => Peter
            [age] => 20
            [city] => Chicago
        )

    [2] => Array
        (
            [name] => John
            [age] => 25
            [city] => New York
        )
)

0
看了该问题的人还看了