php二维数组排序 - php数组排序




PHP按两个字段值排序数组 (4)

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($return_fare, SORT_ASC, $one_way_fare, SORT_ASC, $data);

如果您查看PHP的手册页中有关array_multisort()的注释,您可以找到一个非常有用的array_orderby()函数,它允许您将上述内容array_orderby()为:

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

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

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

我有一个像这样的阵列

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中实现这一点,按field1 asc,field2 asc排序?


另一个使用宇宙飞船运营商的例子。

usort($data, function($a, $b) { 
    return $a['return_fare'] <=> $b['return_fare'] ?: $a['one_way_fare'] <=> $b['one_way_fare'] 
});

或者您可以按如下方式使用uasort

uasort($arr, function($a,$b){
    $c = $a['return_fare'] - $b['return_fare'];
    $c .= $a['one_way_fare'] - $b['one_way_fare'];
    return $c;
});

Fiddle


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

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




sorting