dpmpa26468 2016-06-02 10:00
浏览 39
已采纳

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

I have a JSON returned from the backend service.

$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 has post_id, posted_by and how many likes a post received. I convert it into array for processing in php

$data   =   json_decode($a); 

My array looks like this:

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 is user. and what I'm trying to do is to find how many likes a user received and save that value in a new array. SO, in this case, user 1 received 8 likes and user 3 received 1 like. And,I have to save this in an array.

So, for achieving that, I tried something like this but I didn't get any results. Undefined offset error is shown when the loop executes for the nth time.

$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];
            }

        }

Is there any built in function to do such a check?

  • 写回答

2条回答 默认 最新

  • douji0073 2016-06-02 10:16
    关注

    I would reccomand something like this :

    $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)];
    }
    

    then you would have all the results in $listUserLike

    listUserLike = [ ['user' => 1, 'nbLike' => 8], ['user' => 3, 'nbLike' => 1], ]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号