0

I have two arrays in php, $array1 and $array2, I am ranking $array2 based on $array1

 $array1 =array(2,10,4,5,2,1);
 $array2 =array(A,B,C,D,E,F);



  $ordered_values = $array1;
  array_multisort($array1, $array2);

  foreach ($array1 as $key => $value) {
     foreach ($ordered_values as $ordered_key => $ordered_value) {
       if ($value === $ordered_value) {
        $key = $ordered_key;
        break;
    }
  }


   echo $value . '- Rank: ' . ((int) $key + 1) . '<br/>';

  }

The above gives this results

   1- Rank: 6
   2- Rank: 1
   2- Rank: 1
   4- Rank: 3
   5- Rank: 4
   10-Rank: 2

However this is what I am expecting

    B- Rank: 1
    D- Rank: 2
    C- Rank: 3
    E- Rank: 4
    A- Rank: 4
    F- Rank: 6

Any help is appreciated.

Kevin
  • 41,694
  • 12
  • 53
  • 70
MessiahCoder
  • 111
  • 6

1 Answers1

2

You could array_combine both arrays to line them up and arsort to sort by value and keep the assoc keys. Before the loop setup a counter for the rank number. Also add a temporary holder for the previous value for checking if we want to make the ranking number to hold still and another container of how many skips are done:

$array3 = array_combine($array2, $array1); arsort($array3);
$skip = 0; $i = 0; $temp = null;
foreach($array3 as $k => $v) {
    if($temp !== $v) {$i++; $i += $skip; $skip = 0;}else {$skip++;}
    $temp = $v;
    echo $k, ' Rank: ', $i, "\n";

}

The if condition above just checks if the previous value is not equal. If not, just continue the increment. If its equal add on the skip counter. Then, once the iteration resumes on the non equal, this will merge the skip counter to the current rank number.

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
  • @MessiahCoder sure glad this helped – Kevin Sep 27 '16 at 01:28
  • I have asked a question which has a similar array data in mysql and I want to find the ranking from mysql using find_in_set function or any other better function, kindly see the question if you can be of help http://stackoverflow.com/q/39730507/6855079 – MessiahCoder Sep 27 '16 at 17:15
  • 1
    @MessiahCoder you should accept this answer before asking Ghost to check on another. – Funk Forty Niner Oct 01 '16 at 18:41