1

我想使用 PHP Arrays 计算为给定产品投票的用户数量

输出,是通过以下方式。

对于每个节点应提供“用户数”、“评分”、“评分百分比”。

质量 | 率(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"
        }]
    }, 
4

1 回答 1

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

于 2013-09-04T07:53:10.187 回答