Page 1 of 1

Star Rating

Posted: Wed Aug 29, 2007 1:53 am
by kkonline
I am using

echo $row['votes']+1;
for ($i = 0; $i < (int)$row["rating"]; $i++) {
echo '<img src="rate1.gif">';
}

to show the stars according to the rating.
If i have rating >4.5 then it comes to 4 after type casting and show 4 stars. However i want to show another half star image for anything > 4.49 and below 5 ... or 3.49 and below 4.

That means if the rating is 4.57 then it should show 4 rate1.gif image and then one half star image. How to do this?

Posted: Wed Aug 29, 2007 2:15 am
by s.dot
I did something like this.

Code: Select all

if(!isset($imga['rating']) || ($imga['rating'] == ''))
{
	$rating = 'rating_notrated.gif';
	$ratingalt = 'This image has not yet been rated.';
} else
{
	if($rating = explode('.', $imga['rating']))
	{
		$ratings = (int) $rating[0];
		$ratings_part = $rating[1];
		
		if(strlen($ratings_part) > 2)
		{
			$ratings_part = substr($ratings_part, 0, 2);
		} elseif(strlen($ratings_part) == 1)
		{
			$ratings_part = $ratings_part.'0';
		} elseif(strlen($ratings_part) == 0)
		{
			$ratings_part = '00';
		}
	} else
	{
		$ratings = (int) $imga['rating'];
		$ratings_part = '00';
	}
	
	if($ratings_part < 25)
	{
		$ratings_part = '.gif';
	} elseif($ratings_part < 50)
	{
		$ratings_part = '.5.gif';
	} elseif($ratings_part < 75)
	{
		$ratings_part = '.5.gif';
	} elseif($ratings_part < 100)
	{
		$ratings = $ratings+1;
		$ratings_part = '.gif';
	}
	
	$rating = 'rating_' . $ratings . $ratings_part;
	$ratingalt = 'This image is rated a ' . $ratings . str_replace('.gif', '', $ratings_part) . ' out of 5';
}
This would give me a 0.5.gif, 1.0.gif, 1.5.gif, 2.0.gif, 2.5.gif etc up to 5. It could easily be manipulated to fit your scenario, though.

Posted: Wed Aug 29, 2007 3:33 am
by stereofrog

Code: Select all

$k = round($rating * 2) / 2;
$n = (int) $k;

echo str_repeat("<img star>", $n);
if($n != $k)
	echo "<img half-star>";