如何按特定键对数组进行排序?我有$my_array
,如何按distance
键对其进行排序?为简单起见,数据本身大多不相关和减少。
[0083] => Array
(
[distance] => 28
[url] => http://example.com/
)
[0087] => Array
(
[distance] => 30
[url] => http://example.com/
)
[008e] => Array
(
[distance] => 34
[url] => http://example.com/
)
错误消息消息:无法将标量值用作数组,其中$distance[$k] = $v['distance'];
位于:{/ p>
foreach ($my_array as $k => $v)
{
$distance[$k] = $v['distance'];
$url[$k] = $v['url'];
}
array_multisort($distance, SORT_ASC, $url, SORT_ASC, $my_array);
echo '<pre>';print_r($my_array);echo '</pre>';
答案 0 :(得分:3)
使用usort:
sudo代码:
function sortfunc($a,$b)
{
return $a['distance'] < $b['distance'] ? -1 : $a['distance'] == $b['distance'] ? 0 : 1;
}
usort($yourArray, 'sortfunc');
翻转1和-1以更改排序顺序。
答案 1 :(得分:2)
<?php
$data[] = array('distance' => 34, 'url' => 'http://example.com/');
$data[] = array('distance' => 30, 'url' => 'http://example.com/');
$data[] = array('distance' => 28, 'url' => 'http://example.com/');
$distance = array();
$url = array();
foreach ($data as $key => $row) {
$distance[$key] = $row['distance'];
$url[$key] = $row['url'];
}
array_multisort($distance, SORT_ASC, $url, SORT_ASC, $data);
echo '<pre>';print_r($data);echo '</pre>';
输出:
Array
(
[0] => Array
(
[distance] => 28
[url] => http://example.com/
)
[1] => Array
(
[distance] => 30
[url] => http://example.com/
)
[2] => Array
(
[distance] => 34
[url] => http://example.com/
)
)