Rank per Row values in php

Tags: php
Question!

Is there a way to rank this row of multiple values from mysql using php

row1- (A,B,C) |  (100,200,39)
row2- (A,B,C)  |  (467,29,89)

and wanting the results to look like this

  row1
      rank
  A - 2nd
  B - 1st
  C - 3rd

  row2
      rank
  A  - 1st
  B  - 3rd
  C  - 2nd

Please any ideas as to how to do this? Thanks



Answers

Assuming the array of the mysql looks like this:

$array1=array('A'=>100, 'B'=>200, 'C'=>39);
$array2=array('A'=>467, 'B'=>29, 'C'=>89);

Use arsort:

arsort($array1);
arsort($array2);

The second parameter is: sort_flags

Which uses these types:

SORT_REGULAR - compare items normally (don't change types)

SORT_NUMERIC - compare items numerically

SORT_STRING - compare items as strings

SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()

SORT_NATURAL - compare items as strings using "natural ordering" like natsort()

SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

So you could use arsort($array1,SORT_NUMERIC);

After sorting it, you can loop through it like this:

$x=1;
foreach ($array1 as $key => $val) {
    echo $key.' - '.$x;
    $x++;
}
By : Loko


You have the right idea, basically, but you can greatly simplify your code.

if number < 5:
    print ("You have landed the bottle!")
elif number < 10:
    print ("The bottle did not land, better luck next time.")
else:
    print ("The bottle landed on the cap!")

You can change the values in your call to randrange and in the if statements above to get just about any weighting you'd like.

Note that in your original question you were comparing numbers to strings. I changed that here. Comparing numbers to strings (i.e. 3 == "3") will always be False.



This video can help you solving your question :)
By: admin