简体   繁体   中英

merge array keys and add the values-PHP

I want to merge two same keys in an array and get the sum of the values. I want the same structure as it is now.Because this data needs to be converted to JSON.

This is what i get now.

{ "data": [{ "count_of_invites": 5, "user": "Rajesh", "id": "53" }, { "count_of_invites": 9, "user": "Student", "id": "45" }, { "count_of_invites": 4, "user": "Student", "id": "45" } ] }

As you can see the id 45 are repeated.As i want the result as,

Expected output { "data": [{ "count_of_invites": 5, "user": "Rajesh", "id": "53" }, { "count_of_invites": 13, "user": "Student", "id": "45" } ] }

As you can see the duplicate entry should be removed as well as the count_of_invites of duplicate entry should be added.

You can achieve it this way:

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

The count method was declared as variable and i've added with addition assignment operator.

Thank You for helping.

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM