phparrayssortingassociative-arrayranking

Sort an associative array by values descending and preserve keys then give a ranking number to each key


I have a multidimensional array like this: $person['id'] = $value;

My sample data is like this:

$person[1]=110
$person[2]=200
$person[3]=300
$person[4]=100
$person[5]=220

Right now, I want to sort it by its value, so my array should be like these:

$person[3]=300
$person[5]=220
$person[2]=200
$person[1]=110
$person[4]=100

After this, I want to print it numbers of sorting... So my result would be like these:

$person[3]=1
$person[5]=2
$person[2]=3
$person[1]=4
$person[4]=5

Here's my full code:

$person = array();
$person[1]=110;
$person[2]=200;
$person[3]=300;
$person[4]=100;
$person[5]=220;

rsort($person);
foreach($person as $x => $x_value) {
   echo "Key=" . $x . ", Value=" . $x_value;
   echo "<br>";
}

And that's it, I'm stuck to change the value to what I want. Anyone know how to create a code that I wanted?


Solution

  • Use arsort: Sorts an array in reverse order and maintain index association

    <?PHP
    $person = array();
    $person[1]=110;
    $person[2]=200;
    $person[3]=300;
    $person[4]=100;
    $person[5]=220;
    
    arsort($person);
    $i=0;
    foreach($person as &$p){
        $p=++$i;
    }
    
    var_dump($person);
    

    so your output will be:

    array(5) {
      [3]=>
      int(1)
      [5]=>
      int(2)
      [2]=>
      int(3)
      [1]=>
      int(4)
      [4]=>
      &int(5)
    }