You shouldn't be doing this in PHP. MySQL will do a much better job sorting your results set.
There's a paper here about doing this in MySQL, which is referenced here.
Regardless of which formula you're using, you should be able to do this with MySQL, even if you have to used stored procedures.