问题描述
我有一个这样的数组
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递增的价值,one_way_fare ASC?
How can i sort the value by return_fare asc , one_way_fare asc ?
我试过,但我最终得到混合起来的数据..
I tried array_multisort() but i ended up getting mixed up data..
ASORT只适用于一维数组,我需要两个值以上的排序,我怎么能达到这个SQL一样,为了通过FIELD1 ASC,ASC的field2?
asort only works for one dimensional array, i need to sort by two values or more, how can i achieve this like in SQL, order by field1 asc,field2 asc ?
推荐答案
是正确的功能,必须在一定程度上将搞砸了:
array_multisort()
is the correct function, you must have messed up somehow:
// 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()
功能,可以让你缩短上面眼前这个:
If you take a look at the comments at PHP's manual page for array_multisort()
, you can find a very helpful array_orderby()
function which allows you to shorten the above to just this:
$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
这篇关于PHP数组排序由两个字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!