PHP 排序关联数组

PHP Sort associative array

我有一个这样的关联数组:

$teams_name_points = array();

$name1 = "name1";
$name2 = "name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;

我想按键值对这个数组进行排序,目前它是按键的字母顺序排序的。

我尝试实现自己的排序功能,但不太明白它是如何工作的。

usort($teams_name_points, 'cmp');

function cmp(array $a, array $b){
    if ($a['foo'] < $b['foo']) {
        return -1;
    } else if ($a['foo'] > $b['foo']) {
        return 1;
    } else {
        return 0;
    }
}

如何使比较方法适用于我的数组?

很简单,as per the manual,您只需要接受数组的 作为 cmp() 的参数。

例如

cmp($earlier_array_value, $later_array_value){
    ...
}

另外,当然,请注意 usort() 仅当您 运行 是自定义且非数字直接的比较时才有必要。 >< 的简单比较可以用 existing native sort functions 更容易地完成。

$teams_name_points = array();

$name1 = "name1";
$name2 = "name2";
$teams_name_points[$name1] = 2;
$teams_name_points[$name2] = 1;
print_r($teams_name_points);
asort($teams_name_points); // sort by value low to high
print_r($teams_name_points);
arsort($teams_name_points); // sort by value high to low
print_r($teams_name_points);

使用 asort() 对数组进行排序。

http://php.net/manual/en/function.asort.php

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.