Wil*_*dow 5 php arrays sorting
我得到了这样一个数组:
$input = array(-1,1,3,-2,2, 3,4,-4);
Run Code Online (Sandbox Code Playgroud)
我需要对它进行排序,使得负整数位于前面,正整数位于后面,相对位置不应该改变.所以输出应该是:
$output = array(-1 ,-2,-4, 1,3,2,3,4);
Run Code Online (Sandbox Code Playgroud)
我试过这个usort,但我无法保留相对位置.
function cmp ($a, $b)
{
return $a - $b;
}
usort($input, "cmp");
echo '<pre>', print_r($input), '</pre>';
Array
(
[0] => -4
[1] => -2
[2] => -1
[3] => 1
[4] => 2
[5] => 3
[6] => 3
[7] => 4
)
Run Code Online (Sandbox Code Playgroud)
试试这个..
$arr = array(-1,1,3,-2,2, 3,4,-4);
$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($negative,$positive);
print_r($sorted);
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[0] => -1
[1] => -2
[2] => -4
[3] => 1
[4] => 2
[5] => 3
[6] => 3
[7] => 4
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
585 次 |
| 最近记录: |