简体   繁体   中英

HTML Star rating from value API

Having an challenge, it's been an long time ago since i've used HTML and PHP.

From an 3rd party customer feedback tooling, they provide an API. The Happiness Value is easy to pull from the API and is displayed in an percentage. Nothing more, Nothing less..

<?php include('https://app.customerthermometer.com/api.php?apiKey=********************&getMethod=getHappinessValue'); ?>

I'm wondering and trying to implement this with an PHP Include into an document and make an more colorful and visible view. For example;

http://jsfiddle.net/b6tqtaLn/1/

Star-rating with css

Whats the best way to convert an percentage (eg 95% from API) to an value to be visible in stars?

Thanks in advance!

First of all you need to define how many (max) stars you will be using.

For example if your maximum value from the API you receive is 100%, and you are using 10 stars then it's very easy to do.

Example:

$api_percentage_value = '95%'; // Given from API
$converted_percentage_value = (int) $api_percentage_value; // Make it an integer

echo $converted_percentage_value; // outcome = 95 (integer)

/**
 * Personally I would like to have the 'raw' data to be in a string like above.
 * But if you prefer to have it in a single string simply delete the `$api_percentage_value` and drop the API data inside `$converted_percentage_value` right away.
 * But remember you need to add `(int)` before the result. Otherwise it will not be an integer.
 * Also, incase they do deliver only an integer, it might work for some time.
 * But we all know many API developers just change stuff within their output without communication (before and/or after the change).
 * So I prefer to have it split up and make my own validation.
 */

So, now we have an integer.

Let's say 1 star = 10 points.

The calculation behind this would be:

95 / 100 = 0,95. * 10. = 9.5 (stars) // Incase 1 star = 20 points: simply do 95 / 200, etc.

-OR-

$stars = ($converted_percentage_value / 100) * 10;

echo $stars; // outcome: (int) 9.5

So, now you can display 9.5 (or 9) stars :-).

$score = floor($converted_percentage_value); // outcome: 9.

Now you can do a foreach, and minus $score ($score--) with one everytime. Once $score is below (int) 1 , you can stop your script.

Do you have an idea on how to perform this? Or do you wish to have an example code on displaying a star in a foreach with a countdown?

It seems pretty simple really - you just need to reference each number as a star.

Eg

$value = '95';
$stars = '';

switch($value) {
  case ($value >= '80' && $value <= '100'):
     $stars = '5'
     break;
  case ($value >= '60' && $value <= '79'):
     $stars = '4'
     break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM