2017-07-28 124 views
1

我的代码是这样的:如何计算详细评分的平均评分?

<?php 
    $rating = 5; 
    $rating_detail = '{"3":"1","4":"2"}'; 
    $array_data = json_decode($rating_detail, true); 
    if(array_key_exists($rating, $array_data)) { 
     $value = $array_data[$rating]; 
     if ($value !== false) { 
      $array_data[$rating] = (string)((int)$value + 1); 
     } 
     $rating_detail = json_encode($array_data); 
    } 
    else { 
     $data = substr($rating_detail, 0, -1); 
     $rating_detail = $data.',"'.$rating.'":"1"}'; 
    } 

    echo '<pre>';print_r($rating_detail);echo '</pre>';die(); 
?> 

如果代码运行,其结果是这样的:

{ “3”: “1”, “4”: “2”,“5 “:” 1" }

这是一个商店的详细评价

注:

3 =等级3,1 =用户给出数量的评分:1

4 =等级4,2 =用户给出数量的评分:2

5 =评级5,1 =用户数量给予的评分:1

如何计算详细评分的平均评分?

因此,一个商店的细节等级的平均等级为1之间 -

所以从这里5

更新:

{ “3”: “1”,“4 “:”2“,”5“:”1“}

根据该评级的详细信息,如何计算商店的评分?

+0

什么是你预期的结果? – Val

+1

你不知道__average__是什么? –

+0

@Val,'{“3”:“1”,“4”:“2”,“5”:“1”}' –

回答

2

尝试这样

$rating = 5; 
$rating_detail = '{"3":"1","4":"2"}'; 
$rating_detail = json_decode($rating_detail, true); 
if(array_key_exists($rating, $rating_detail)) { 
     $rating_detail[$rating] = (string)((int)$rating_detail[$rating] + 1); 
} 
else { 
    $rating_detail[$rating]="1"; 
} 
$totalStar=$totalRate=0; 
foreach ($rating_detail as $key=>$value){ 
    $totalStar+=$key*$value; 
    $totalRate+=$value; 

} 
$average=$totalStar/$totalRate; 

它给放出来作为

enter image description here

+0

@Success Man你试过这个吗? –

+0

太好了。有用。谢谢 –

+0

快乐是我的:) –