在PHP数组中仅排序非零值[重复]

This question already has an answer here:

I want to sort only those values in array which are not 0 and all 0 values key should be at bottom. so for example if our array is like this-

array
{
    [0]=>4
    [1]=>0
    [2]=>2
    [3]=>0
    [4]=>3
}

So sorted array I should get like below

array
{
    [2]=>2
    [4]=>3
    [0]=>4
    [1]=>0
    [3]=>0
}
</div>

Using a custom sort function you could use:

function usortTest($a, $b) {

    if( $a == 0 ) return 1;
    if( $b == 0 ) return -1;

    return gmp_cmp($a, $b);

}

$test = array(4,0,2,0,3);
usort($test, "usortTest");

print_r($test);

May need to be refactored/improved, but the documentation should help you understand custom sort functions.

There is a PHP function call uasort that lets you define a function to sort an array and maintain array key ordering.

The return value of your defined function must be 0, -1 or 1 depending on if the values are the same, if the second value is less than the first value, or if the second value is greater than the first value, respectively.

To achieve what you are attempting would require a function similar to:

$array = array(4,0,2,0,3);
uasort($array, function($a,$b) {
    // push all 0's to the bottom of the array
    if( $a == 0 ) return 1;
    if( $b == 0 ) return -1;   
    if($a == $b) {return 0; }   // values are the same
    return ($a < $b) ? -1 : 1;  // smaller numbers at top of list
});
var_dump($array);
/*
array (size=5)
  2 => int 2
  4 => int 3
  0 => int 4
  3 => int 0
  1 => int 0
*/

Use uasort() function:

$arr = array(
    4, 0, 2, 0, 3
);

uasort($arr, function($a, $b){
    if ($a == 0) {
        return 1;
    }
    if ($b == 0) {
        return -1;
    }
    return ($a < $b) ? -1 : 1;
});

print_r($arr);

Or go with what @axiac said:

$a = array(4, 0, 2, 0, 3);

function getZeros(&$a) {
    $zeros = array();
    for($i = 0; $i < count($a); $i++) {
        if($a[$i] === 0) {
            $zeros[] = 0;
            unset($a[$i]);
        }
    }

    return $zeros;
}

$zeros = getZeros($a);
sort($a);
$a = array_merge($a, $zeros);

echo join(', ', $a);