使用fmod()

时间:2018-05-19 06:30:28

标签: php laravel

我有一个评级数组,其中有一个特定产品的评级列表,我想要的结果是平均评分。

我想要达到的目标是,如果平均评分为4.2 or 4.3或介于4 to 4.5之间,则应为4.5,如果平均评分为4.6或4.7,则应评为5等级。

如果平均等级为4.2或4.6,我已经完成了4.5的结果。

$product_ratings = Array
                  (
                     [0] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 5
                        [user_id] => 154
                     )
                     [1] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 5
                        [user_id] => 154
                     )
                     [2] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 3.5
                        [user_id] => 154
                     )
                     [3] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 5
                        [user_id] => 154
                     )
                     [4] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 2.5
                        [user_id] => 154
                     )
                     [5] => stdClass Object
                     (
                        [id] => 93
                        [product_id] => 5
                        [rating] => 4.5
                        [user_id] => 154
                     )
                   )
                $r = 0;
                $rating_total="";
                foreach ($product_ratings as $row) {
                    $rating_total += $row->rating;
                    $r++;
                }
                $average_rating = "";     
                if($rating_total != "" || $rating_total != 0)
                {
                    $average_rating = $rating_total / $r;
                }
                else
                {
                    $average_rating = 0;
                }
                $avg_rating = $average_rating - fmod($average_rating, 0.5);
                echo $avg_rating

0 个答案:

没有答案