用于转换星级评定值的PHP代码[关闭]

I have given rating values form 1.0 to 6.0. Here 1.0 is the best and 6.0 is the baddest rating. I have to convert the ratings like this. If 1.0 is the given rating value i will have to show 5.0 and IF 6.0 is the given rating value i will have to show 1.0 So if 3.0 is the given rating value i will have to show 2.5 and so on.I am grabbing this 1 to 6 ratings from an external website. Need to convert it to 1 to 5 to my website.

This is more about math than it is about php.

So let's see, first we need to reverse the values. Because we want change on which end of the rating is worst and best respectively.

$reverseRating = 7.0 - $inputRating;

This transforms 1.0 into 6.0 and 6.0 into 1.0 etc.

Now all left to do is scale the values down from 6 stars (input range: 6 - 1 = 5.0) into 5 stars (output range: 5 - 1 = 4.0). For that we will shift everything down to 0, shrink it, then shift it back to 1.

$outputRating = ($reverseRating - 1.0) / 5.0 * 4.0 + 1.0;

Written as compact one-liner this results in

$outputRating = (6.0 - $inputRating) * 0.8 + 1.0;

Note

Your conclusion that the input 3.0 should result in 2.5 is wrong.

Because the lowest value is 1, not 0, the center value on the input rating scale is not 3, it is 3.5:

6 5 4 (3.5) 3 2 1

Same goes for the output center value, it's not 2.5, it is 3:

1 2 3 4 5

3.0 on input is actually slightly better than center and will map to 3.4 on output.