2

コンポーネントK2を使用しています。これは投票/評価システムです。現在、評価をパーセンテージで表示し、星を表示するための css をいくつか使用しています。しかし、星を表示する代わりに、たとえば 4.5/5 と言ってほしい

これを表示するためのコードは次のとおりです。

<?php if($this->item->params->get('catItemRating')): ?>
<div id="catItemRatingBlock">
 <div class="itemRatingForm">
   <ul class="itemRatingList">
     <li class="itemCurrentRating" id="itemCurrentRating<?php echo $this->item->id; ?>" style="width:<?php echo $this->item->votingPercentage; ?>%;"></li>
     <li><a href="#" rel="<?php echo $this->item->id;  ?>" class="one-star">1</a></li>
     <li><a href="#" rel="<?php echo $this->item->id;  ?>" class="two-stars">2</a></li>
     <li><a href="#" rel="<?php echo $this->item->id;  ?>" class="three-stars">3</a></li>
     <li><a href="#" rel="<?php echo $this->item->id;  ?>" class="four-stars">4</a></li>
     <li><a href="#" rel="<?php echo $this->item->id;  ?>" class="five-stars">5</a></li>
   </ul>
 </div>
</div>
<?php endif; ?>

そして、これは「com_k2/models/item.php」にあるコードです:

function getVotesPercentage($itemID = NULL)
{

    $mainframe = &JFactory::getApplication();
    $user = JFactory::getUser();
    $db = &JFactory::getDBO();
    $xhr = false;
    $result = 0;
    if (is_null($itemID))
    {

        $itemID = JRequest::getInt('itemID');
        $xhr = true;
    }

    $vote = K2ModelItem::getRating($itemID);

    if (!is_null($vote) && $vote->rating_count != 0)
    {
        $result = number_format(intval($vote->rating_sum) / intval($vote->rating_count), 2) * 20;
    }
    if ($xhr)
    {
        echo $result;
        $mainframe->close();
    }
    else
        return $result;
}

私は何をすべきか?

4

1 に答える 1

1

要約すると、 $this->item->votingPercentage (0 から 100) に示されているパーセンテージを取得し、それを 20 で割って 0 から 5 の範囲の数値に変換します。数値を 5 段階中 x として表示するときの正確さの場所。

VotingPercentage が文字列なのか数値なのかわからないので、計算を行う前に有効な数値であることをテストします。

<?php

if (!isnumeric($this->item->votingPercentage) {

   $numericRating = 0;

// If the value cannot be interpreted as a numeric, we assume a value of 0.

}

else {

   $numericRating = round(($this->item->votingPercentage / 2), 0);  

// The statement above is equivalent to dividing the percentage by 20 (to get a number from 0 to 5); and then multiplying by 10 to get a number from 0 to 50.  Since this final number could have a decimal component (for example 42.55 out of 50), we round to 0 decimal places to get rid of the decimal remainder - in this example, resulting in the number 43

   $numericRating = round(($numericRating / 10), 1);

// The statement above divides the number from the previous step by 10 (to shift the decimal point), and just for good measure, applies the rounding function one more time in case the division yields a number like 4.300000001 or 4.29999999

}

echo $numericRating . "/5";

// Finally, the resulting numeric value is rendered as a number from 0 to 5 with 1 decimal place, followed by the characters "/5"  (i.e. out of 5)
?>
于 2012-08-23T03:48:07.117 に答える