我想计算使用PHP数组投票给定产品的用户数
输出,采用以下方式。
对于每个节点,应提供“用户数”,“评级”,“评级百分比”。
质量|率(4星)| NUMBER_OF_USERS(4) 代码|率(4星)| NUMBER_OF_USERS(2) 率|率(4星)| NUMBER_OF_USERS(2)以下是json格式的投票数组,
{
"reviews": [{
"nick_name": "vishnu",
"voteArr": [{
"code": "Quality",
"rate": "4"
}, {
"code": "Value",
"rate": "4"
}, {
"code": "Price",
"rate": "4"
}]
}, {
"nick_name": "smerphy",
"voteArr": [{
"code": "Quality",
"rate": "4"
}, {
"code": "Value",
"rate": "4"
}, {
"code": "Price",
"rate": "4"
}]
},
答案 0 :(得分:0)
试试这个:
$encoded = '{
"reviews": [
{
"nick_name": "vishnu",
"voteArr": [
{
"code": "Quality",
"rate": "2"
},
{
"code": "Value",
"rate": "4"
},
{
"code": "Price",
"rate": "3"
}
]
},
{
"nick_name": "smerphy",
"voteArr": [
{
"code": "Quality",
"rate": "1"
},
{
"code": "Value",
"rate": "4"
},
{
"code": "Price",
"rate": "1"
}
]
}
]
}';
$ratings = json_decode($encoded);
foreach($ratings->reviews as $rating)
{
$avg = 0;
foreach($rating->voteArr as $value) {
$avg += $value->rate;
}
$avg = round($avg/count($rating->voteArr));
echo $rating->nick_name." voted ".$avg."<br />";
}
vishnu voted 3
smerphy voted 2