john
john

Reputation: 11709

How to show star ratings in css when rating is known?

I am working on a website in which to show star ratings when rating in known. Below is the JSON object having all necessary information:

"item_ratings": [{
    "rating_id": 26,
    "item_id": 333,
    "booking_id": 60,
    "owner_id": null,
    "renter_id": 38,
    "rating": 5,
    "rating_type": "item",
    "created_at": "2018-07-04 10:28:55",
    "updated_at": "2018-07-04 10:28:55",
}, {
    "rating_id": 15,
    "item_id": 333,
    "booking_id": null,
    "owner_id": null,
    "renter_id": 38,
    "rating": 4,
    "rating_type": "item",
    "created_at": "2018-01-17 10:16:58",
    "updated_at": "2018-01-17 10:16:58",
}]

The code which I am using in php in order to pull the rating is:

for ($i = 0; $i < count($data['item']->item_details->item_ratings); $i++) 
{
echo '<p class="renter_review_ratings">'.strtolower($data['item']->item_details->item_ratings[$i]->rating).'</p>';
}


Problem Statement:

I am wondering what changes I need to make in the php code above so that when it is 4, it should display 4 stars, when it is 3 it should display 3 stars and vice versa.

Upvotes: 0

Views: 380

Answers (2)

Lachie
Lachie

Reputation: 1411

Given that you use FontAwesome 5 and your rating is out of 5 stars, the following code should work.

for ($j = 0; $j < count($data['item']->item_details->item_ratings); $j++) {
  $rating = $data['item']->item_details->item_ratings[$j]->rating;
  for($i = 1;$i <= 5;$i++) {
    if ($rating >= $i) {
      echo "<i class='fas fa-star'></i>";
    } else {
      echo "<i class='far fa-star'></i>";
    }
  }
}

What is happening here is that, we have the first for loop that gets all the ratings. It then has another nested for loop that loops exactly 5 times. Each time it looks it uses an if statement to determine whether to show a full star or an empty star using the FontAwesome library.

Upvotes: 3

Jagjeet Singh
Jagjeet Singh

Reputation: 1572

As per your json you can do like this :-

for ($i = 0; $i < count($data['item']->item_details->item_ratings); $i++) 
{
    for($j = 0; $j < 5; $j++)
    {
        if($j <= $data['item']->item_details->item_ratings[$i]->rating) {
            // Star code
        } else {
            // No star code
        }
    }
}

Upvotes: 1

Related Questions