使用array_multisort对多维数组进行排序
问题描述:
我有这个数组
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.
答
您需要先提取所有距离,然后将距离和数据都传递给函数.如 array_multisort 文档中的示例3所示.
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_multisort documentation.
foreach ($data as $key => $row) {
$distance[$key] = $row['distance'];
}
array_multisort($distance, SORT_ASC, $data);
这假设您首先要最短的距离,否则将SORT_ASC
更改为SORT_DESC
This assumes you want the shortest distances first, otherwise change the SORT_ASC
to SORT_DESC