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

avatar
作者
猴君
阅读量:0

可以使用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         ) ) 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!