优雅的方式来排序这样的数组

Ric*_*nop 4 php arrays sorting

这是我的阵列:

$arr = array(-3, -4, 1, -1, 2, 4, -2, 3);
Run Code Online (Sandbox Code Playgroud)

我想这样排序:

1
2
3
4
-1
-2
-3
-4
Run Code Online (Sandbox Code Playgroud)

因此,首先会有从最低值到最高值排序的值大于零的值,然后会有从最高值到最低值排序的负值.

有一些优雅的方式来做到这一点?

sal*_*the 10

这是一个简单的比较功能:

function sorter($a, $b) {
    if ($a > 0 && $b > 0) {
        return $a - $b;
    } else {
        return $b - $a;
    }
}

$arr = array(-3, -4, 1, -1, 2, 4, -2, 3);
usort($arr, 'sorter');
var_dump($arr);
Run Code Online (Sandbox Code Playgroud)

旁白:有了上述,零落在围栏的负面.更改>>=,如果你希望他们上升到积极的一面的顶部所述栏.


Bol*_*ock 6

这是一种非usort()方法,假设零无关紧要......

<?php

$arr = array(-3, -4, 1, -1, 2, 4, -2, 3);

$positive = array_filter($arr, function($x) { return $x > 0; });
$negative = array_filter($arr, function($x) { return $x < 0; });

sort($positive);
rsort($negative);

$sorted = array_merge($positive, $negative);
print_r($sorted);

?>
Run Code Online (Sandbox Code Playgroud)

编辑:没有PHP 5.3?create_function()按照你的说法使用:

$positive = array_filter($arr, create_function('$x', 'return $x > 0;'));
$negative = array_filter($arr, create_function('$x', 'return $x < 0;'));
Run Code Online (Sandbox Code Playgroud)