PHP 按两个字段值排序数组

2022-08-30 08:10:57

我有一个这样的数组

Array (
 [0] => Array( "destination" => "Sydney",
               "airlines" => "airline_1",
               "one_way_fare" => 100,
               "return_fare => 300
       ),
 [2] => Array( "destination" => "Sydney",
               "airlines" => "airline_2",
               "one_way_fare" => 150,
               "return_fare => 350
       ),
 [3] => Array( "destination" => "Sydney",
               "airlines" => "airline_3",
               "one_way_fare" => 180,
               "return_fare => 380
       )
)

如何按return_fare asc , one_way_fare asc 对值进行排序?

我尝试array_multisort()但我最终得到了混淆的数据。

asort仅适用于一维数组,我需要按两个值或更多值进行排序,我如何实现像SQL,按字段1 asc排序,字段2 asc?


答案 1

array_multisort() 是正确的函数,你一定以某种方式搞砸了:

// Obtain a list of columns
foreach ($data as $key => $row) {
    $return_fare[$key]  = $row['return_fare'];
    $one_way_fare[$key] = $row['one_way_fare'];
}

// Sort the data with volume descending, edition ascending
array_multisort($data, $return_fare, SORT_ASC, $one_way_fare, SORT_ASC);

如果你看一下PHP手册页上的评论,你可以找到一个非常有用的函数,它允许你把上面的内容缩短为:array_multisort()array_orderby()

$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);

要避免循环使用(从 PHP 5.5.0 开始):array_column()

array_multisort(array_column($data, 'return_fare'),  SORT_ASC,
                array_column($data, 'one_way_fare'), SORT_ASC,
                $data);

答案 2

除了 需要您首先构建列数组之外,还有 usort() 不需要这样的东西。array_multisort()

usort($data, function($a, $b) { 
    $rdiff = $a['return_fare'] - $b['return_fare'];
    if ($rdiff) return $rdiff; 
    return $a['one_way_fare'] - $b['one_way_fare']; 
}); // anonymous function requires PHP 5.3 - use "normal" function earlier