找到使用PHP投票给定产品的用户数量

时间:2013-09-04 07:32:47

标签: php

我想计算使用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"
        }]
    }, 

1 个答案:

答案 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

演示键盘: http://codepad.org/aOjvV0mS