Basically i am trying to do a simple 5 star rating system, using font awesome classes for the stars.
Full star
<i class="fa fa-star"></i>
No star
<i class="fa fa-star-0"></i>
Half star
<i class="fa fa-star-half-0"></i>
So i loop through each review for my service like seen below:
$i=0;
$reviewRating = 0;
foreach($service['reviews'] as $review){
$i++;
$reviewRating += $review['rating'];
}
From this i now have the amount of reviews and the total of all review ratings added together.
I pass both of these values into my function as seen below:
function get_rating_stars($reviewRating,$i){
//rounding number to nearest .5
$rating = round($reviewRating/$i * 2) / 2;
$cnt = 0;
$class = "";//class active gives the star a colour, if empty it shows as a empty star.
$zeros = false;//this is for when we have gone past the .5 meaning any further stars have to be a zero(empty star).
$starList ="";//This will be returned when built up
while($cnt < 5){//because there will always be 5 stars showing, regardless to full half or empty
if($zeros){
$starList.= '<li><i class="fa fa-star-o"></i></li>';
$cnt++;
}else{
if($rating == 0.5){
$starList.= '<li class="active"><i class="fa fa-star-half-o"></i></li>';
$zeros = true;//now we have output the half star all following will be empty
$cnt++;
}else{
//the first loop will normally start here unless rating starts at 0.5
if($rating > 0.5){$class = "active";}else{$class = "";}
$starList.= '<li class="'. $class .'"><i class="fa fa-star"></i></li>';
$cnt++;
$rating--;
}
}
}
return $starList;
}
So this function i made does do the trick and works exactly how i want it too, however that it has to repeat this process for every single service on the page. So when i loop through all services i loop through each review and do this, it just seems a bit over kill.
This function could theoretically get called 20 times , as i can show up to 20 services on one page.
Does anyone know how i can make this more efficient?