PHP array_multisort按键递增

时间:2015-11-30 17:29:40

标签: php sorting

如何按特定键对数组进行排序?我有$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>';

2 个答案:

答案 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)

使用array_multisort()

<?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/
        )        
)