MessiahCoder - 2 years ago 105
PHP Question

# Ranking two arrays in order based on anther array

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download