合并数组键并添加值-PHP

时间:2018-06-18 10:16:26

标签: php arrays arraylist merge key

我想在数组中合并两个相同的键并获取值的总和。 我想要与现在相同的结构。因为这些数据需要转换为JSON。

这就是我现在所能得到的。

{     "数据":[{             " count_of_invites":5,             "用户":" Rajesh",             " id":" 53"         },         {             " count_of_invites":9,             "用户":"学生",             " id":" 45"         },         {             " count_of_invites":4,             "用户":"学生",             " id":" 45"         }     ] }

正如你所看到的那样,id 45重复出现。我想把结果作为,

预期输出 {     "数据":[{             " count_of_invites":5,             "用户":" Rajesh",             " id":" 53"         },         {             " count_of_invites":13,             "用户":"学生",             " id":" 45"         }     ] }

正如您所看到的那样,应该删除重复的条目,并且应该添加重复条目的 count_of_invites

3 个答案:

答案 0 :(得分:0)

你可以这样做:

$ids = array();
$output = array();

foreach ($input as $value) {
    if (!isset($ids[$value["id"]])) {
        $ids[$value["id"]]=$count($output);
        $output[]=$value;
    } else {
        $output[$ids[$value["id"]]]["count_of_invites"] = $value["count_of_invites"];
        $output[$ids[$value["id"]]]["user"] = $value["user"];
    }
}

答案 1 :(得分:0)

count方法被声明为变量,我添加了附加赋值运算符。

感谢您的帮助。

$ ids = array();         $ output = array();

    foreach ($response as $value) {
        if (!isset($ids[$value["id"]])) {
            $ids[$value["id"]] = count($output);
            $output[]          = $value;
        }
        else {
            $output[$ids[$value["id"]]]["count_of_invites"] += $value["count_of_invites"];
            $output[$ids[$value["id"]]]["user"]             = $value["user"];
        }
    }

答案 2 :(得分:0)

<?php
$data = [
    [
        'id' => 2,
        'name' => 'Paul',
        'count' => 4
    ],
    [
        'id' => 3,
        'name' => 'Peter',
        'count' => 5
    ],
    [
        'id' => 3,
        'name' => 'Peter',
        'count' => 7
    ]
];

foreach($data as $array)
    $counts[$array['id']][] = $array['count'];

$counts = array_map('array_sum', $counts);
foreach($data as $k => $array)
    $data[$k]['count'] = $counts[$array['id']];

$data = array_unique($data, SORT_REGULAR);
print json_encode($data, JSON_PRETTY_PRINT);

输出:

[
    {
        "id": 2,
        "name": "Paul",
        "count": 4
    },
    {
        "id": 3,
        "name": "Peter",
        "count": 12
    }
]
相关问题