php-检查2个元素相同并找到总和

时间:2016-06-02 10:00:20

标签: php arrays json

我从后端服务返回了一个JSON。

$a='{
    "post_id": [
        "1",
        "34",
        "29",
        "35",
        "28",
        "37"
    ],
    "posted_by": [
        "1",
        "1",
        "1",
        "1",
        "1",
        "3"
    ],
    "total_likes": [
        4,
        1,
        1,
        1,
        1,
        1
    ]
}';

JSON有post_id,posted_by以及有多少人喜欢收到的帖子。 我将其转换为数组以便在php中进行处理

$data   =   json_decode($a); 

我的数组看起来像这样:

stdClass Object
(
    [post_id] => Array
        (
            [0] => 1
            [1] => 34
            [2] => 29
            [3] => 35
            [4] => 28
            [5] => 37
        )

    [posted_by] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 1
            [3] => 1
            [4] => 1
            [5] => 3
        )

    [total_likes] => Array
        (
            [0] => 4
            [1] => 1
            [2] => 1
            [3] => 1
            [4] => 1
            [5] => 1
        )

)

posted_by是用户。而我想要做的是找到用户收到多少喜欢并将该值保存在新阵列中。因此,在这种情况下,用户1收到8个喜欢而用户3收到1喜欢。而且,我必须将其保存在一个数组中。

所以,为了达到这个目的,我尝试了类似的东西,但我没有得到任何结果。循环执行第n次时显示未定义的偏移量错误。

$total_likes=0;
        $data2=array();

        for($j=0; $j<sizeof($data['posted_by']);$j++)
        {
            if($data['posted_by'][$j] == $data['posted_by'][$j+1])
            {
                $data2[$j]['user']      =   $data['posted_by'][$j];
                $data2[$j]['likes']     =   $total_likes + $data['total_likes'][$j];
            }

        }

是否有内置功能进行此类检查?

2 个答案:

答案 0 :(得分:1)

我会重新做这样的事情:

$data = json_decode($a);
// list of all user sid
$users = array_unique($data['posted_by']);
$listUserLike = [];

foreach($users as $user) {
    $indexes = array_keys($data['posted_by'], $user);
    $likes = array_intersect_key($data['total_likes'], array_flip($indexes));
    $listUserLike[] = ['user' => $user, 'nbLike' => array_sum($likes)];
}

那么你将获得$ listUserLike

中的所有结果

listUserLike = [    ['user'=&gt; 1,'nbLike'=&gt; 8],    ['user'=&gt; 3,'nbLike'=&gt; 1], ]

答案 1 :(得分:0)

试试这个:

$cnt = 0;
$temp = array();
$newArr = array();
foreach($data['posted_by'] as $user) {
    if(in_array($user, $temp)) {
        $newArr[$user] = $newArr[$user] + $data['total_likes'][$cnt];
    } else {
        $temp[$user] = $user;
        $newArr[$user] = $data['total_likes'][$cnt];
    }
    $cnt++;
}
print '<pre>';print_r($newArr);
exit;