在PHP中对关联数组进行排序

时间:2015-07-14 11:35:35

标签: php arrays

苦苦于对这个数组进行排序:

它是数据库驱动的,它被添加如下:

$distanceArray[] = array($attractionID => $tempDistance);

,使用pre标签的输出如下:

Array
(
    [0] => Array (
        [4] => 114.4
    )

    [1] => Array (
        [3] => 16.1
    )

    [2] => Array (
        [2] => 15
    )

    [3] => Array (
        [1] => 21.4
    )
)

我试过这个没有运气:

function cmp($a, $b)
{
    return $a['tempDistance'] - $b['tempDistance'];
}

usort($distanceArray, "cmp");
来自w3学校的krsort

2 个答案:

答案 0 :(得分:1)

试试这个......

 $test = array( 
              array(4=>"114.4"),
              array(3=>"16.1"),
              array(2=>"15"),
              array(1=>"21.4"),     

            );

   $value = array();
foreach ($test as $key => $row)
{
    $value[$key] = array_values($row);
}
array_multisort($value, SORT_ASC,$test);

    print_r($value);

答案:数组([0] =>数组([0] => 15)[1] =>数组([0] => 16.1)[2] =>数组([0] => 21.4)[3] =>数组([0] => 114.4))

样本:https://eval.in/398469

答案 1 :(得分:0)

我使用了以下内容:

        asort($distanceArray);
        foreach ($distanceArray as $key => $tempDistance) {
            echo "$key = $tempDistance\n";
        }

打印:

  

2 = 15 3 = 16.1 1 = 21.4 4 = 114.4

感谢您抽出时间帮我解决这个问题!