PHP sorting issue, arsort vs asort + array

I was recently working on one of the project euler problem sets and came across this strange issue. I've solved the problem correctly with the first solution, but I don't know why the other version does not work as expected.

Here is the code that works:

asort($card_count, SORT_NUMERIC);
$card_count = array_reverse($card_count, true);

And here is the code that does not:

arsort($card_count, SORT_NUMERIC);

This is the only line i change and it makes a huge difference in the end result. Any ideas whats up with this?


The issue arises with sorting equal values in the array. Take the array:

$arr = array(
    'a' => 1,
    'b' => 1,
    'c' => 1,
    'd' => 1
);

Calling asort($arr, SORT_NUMERIC) on this array will reverse the array . Hence, the lines of code:

asort($arr, SORT_NUMERIC);
$arr = array_reverse($arr, true);

will put the array back in the original order .

So, adding in one value that's higher with change the array as such:

$arr = array(
    'a' => 1,
    'b' => 1,
    'c' => 2,
    'd' => 1
);

asort($arr, SORT_NUMERIC);
$arr = array_reverse($arr, true);

will yeild:

Array
(
    [c] => 2
    [a] => 1
    [b] => 1
    [d] => 1
)

while

arsort($arr, SORT_NUMERIC);

will yeild:

Array
(
    [c] => 2
    [d] => 1
    [b] => 1
    [a] => 1
)

Hopefully this sheds some light on the issue ...

链接地址: http://www.djcxy.com/p/61816.html

上一篇: 获取所有组的用户是通过oauth(谷歌)的成员,

下一篇: PHP排序问题,arsort vs asort +数组