php 使用 array_multisort 对多维数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5305594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort a multidimensional array using array_multisort
提问by dst11
I have this array
我有这个数组
Array
(
[0] => Array
(
[brand] => blah blah
[location] => blah blah
[address] => blah blah
[city] => blah blah
[state] => CA
[zip] => 90210
[country] => USA
[phone] => 555-1212
[long] => -111
[lat] => 34
[distance] => 3.08
)
[1] => Array
(
[brand] => blah blah
[location] => blah blah
[address] => blah blah
[city] => blah blah
[state] => CA
[zip] => 90210
[country] => USA
[phone] => 555-1212
[long] => -111
[lat] => 34
[distance] => 5
)
.
.
.
}
I want to be able to sort the arrays in the hash by distance.
我希望能够按距离对散列中的数组进行排序。
回答by Jacob
You need to extract all the distances first, then pass both the distance and the data to the function. As shown in example 3 in the array_multisortdocumentation.
您需要先提取所有距离,然后将距离和数据都传递给函数。如array_multisort文档中的示例 3 所示。
foreach ($data as $key => $row) {
$distance[$key] = $row['distance'];
}
array_multisort($distance, SORT_ASC, $data);
This assumes you want the shortest distances first, otherwise change the SORT_ASC
to SORT_DESC
这假设您首先想要最短距离,否则将更SORT_ASC
改为SORT_DESC
回答by Chirag Viradiya
If you want to avoid the looping you can use the array_column
function to achieve your target.
For Example,
如果您想避免循环,您可以使用该array_column
功能来实现您的目标。例如,
You want to sort below array with distance sort
您想使用距离排序在数组下方进行排序
$arr = array(
0 => array( 'lat' => 34, 'distance' => 332.08 ),
1 => array( 'lat' => 34, 'distance' => 5 ),
2 => array( 'lat' => 34, 'distance' => 34 )
);
Using below single line your array will be sort by distance
使用下面的单行,您的数组将按距离排序
array_multisort( array_column( $arr, 'distance' ), SORT_ASC, SORT_NUMERIC, $arr );
Now, $arrcontain with sortedarray by distance
现在,$arr包含按距离排序的数组
回答by Czechnology
回答by karthikeyan ganesan
This code helps to sort the multidimensional array using array_multisort()
此代码有助于使用array_multisort()对多维数组进行排序
$param_dt = array();
foreach ($data_set as $key => $row) {
if(isset($row['params']['priority']))
{
$param_dt[$key] = $row['params']['priority'];
}
else
{
$param_dt[$key] = -2; // if priority key is not set for this array - it first out
}
}
array_multisort($param_dt, SORT_ASC,SORT_NUMERIC, $data_set);
Now $data_set
has the sorted list of elements.
现在$data_set
有元素的排序列表。