PHP asort按值ASC排序数组项?

时间:2015-02-28 06:11:44

标签: php arrays asort

asort很奇怪,我想根据它们的值对数组中的项进行排序,

$items = Array ( "1" => 10 , "11" => 10, "22" => 10 );

// Sort an array and maintain index association.
asort($items);

var_dump($items);

因为所有值相同,所以asort 不应该做任何事情(我假设),但我得到的结果,< / p>

array (size=3)
  22 => string '10' (length=2)
  11 => string '10' (length=2)
  1 => string '10' (length=2)

撤销订单!?为什么呢?

我想要什么(我认为它应该是这样的),

array (size=3)
  1 => string '10' (length=2)
  11 => string '10' (length=2)
  22 => string '10' (length=2)

有什么想法吗?

编辑:

我试过这个,

// Comparison function
private function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

...

// Sort an array and maintain index association.
uasort($items, array($this, "cmp"));

但我仍然得到相同的错误&#39;结果....

1 个答案:

答案 0 :(得分:1)

由于版本4.1.0 PHP sort is not stable由于排序算法,因此无法同时考虑值和密钥。在值相等的情况下,您必须使用自己的比较实现来考虑密钥。例如,您可以将原始数组值修改为(键,值)对,排序数组并将其转换为单维背面。

$items = ["1" => 10, "11" => 10, "22" => 10];

$callback = function ($a, $b) use ($callback) {
    $result = $a['value'] - $b['value'];

    if ($result == 0) {
        $result = $a['key'] - $b['key'];
    }

    return $result;
};

array_walk($items, function (&$value, $key) {
    $value = ["key" => $key, "value" => $value];
});

usort($items, $callback);

$items = array_combine(array_column($items, 'key'), array_column($items, 'value'));

print_r($items);