0

Hello how to sort arrays by keys and values too... so if user input this value

$input = array(0,1,0,2,0);

then the result should be like this since they're the same input they should maintain their keys too...

Array
(
    [0] => 0
    [2] => 0
    [4] => 0
    [1] => 1
    [3] => 2
)

not like this... the keys is jumbled and I really that key to work on my project of FCFS Scheduling.

Array
(
    [4] => 0
    [0] => 0
    [2] => 0
    [1] => 1
    [3] => 2
)

btw I used asort. someone help me how to fix this?

3 Answers3

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

$a = array(0,1,0,2,0);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo " $value\n";
}
Vandana Pareek
  • 226
  • 2
  • 13
0

Stable sort would help here. But php don't have any stable sorting functions since 4.1. But you can use uksort + closure.

$input = array(0,1,0,2,0);

$cmp = function($a, $b) use($input){
    if($input[$a] > $input[$b]){return 1;}
    elseif($input[$a] < $input[$b]){return -1;}
    elseif($a>$b){return 1;}
    elseif($a<$b){return -1;}
    return 0;
};

uksort($input, $cmp);

print_r($input);

https://eval.in/145923

Or shorter version

$cmp = function($a, $b) use($input){
    return (($input[$a]-$input[$b])?:($a-$b));
};
mleko
  • 9,108
  • 5
  • 41
  • 68
-1

Simple use the sort function

$input = array(0,1,0,2,0);

sort($input);

Result:-
    Array
    (
        [0] => 0
        [1] => 0
        [2] => 0
        [3] => 1
        [4] => 2
    )
Lalit Patel
  • 98
  • 1
  • 8