我有这样的数组
数组( [0] => Array(“ destination” =>“ Sydney”, “ airlines” =>“ airline_1”, “ one_way_fare” => 100, “返回票价=> 300 ), [2] => Array(“ destination” =>“ Sydney”, “ airlines” =>“ airline_2”, “ one_way_fare” => 150, “返回票价=> 350 ), [3] => Array(“ destination” =>“ Sydney”, “ airlines” =>“ airline_3”, “ one_way_fare” => 180, “返回票价=> 380 ) )
如何按return_fare asc和one_way_fare asc排序值?
我尝试了array_multisort()但最终却得到了混乱的数据。
Asort仅适用于一维数组,我需要按两个或多个值进行排序,我如何才能像SQL中那样实现此功能,按field1 asc,field2 asc排序?
array_multisort() 是正确的函数,您必须以某种方式搞砸了:
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_column()
array_multisort(array_column($data, 'return_fare'), SORT_ASC, array_column($data, 'one_way_fare'), SORT_ASC, $data);