0

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.

Kiran JB
  • 1
  • 3
  • 3
    Possible duplicate of [Sum array values of the same key](https://stackoverflow.com/questions/1496682/sum-array-values-of-the-same-key) – Masivuye Cokile Jun 18 '18 at 10:17
  • Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve). – Federico klez Culloca Jun 18 '18 at 10:18
  • What have you tried? This does not look too complicated – Nico Haase Jun 18 '18 at 10:21
  • yeah i know its not complicated but i've used some array function as well as loops but it doesn't end up in the desired result. – Kiran JB Jun 18 '18 at 10:31
  • Then post what you have tried. And please include the array in json or var_export format. – Andreas Jun 18 '18 at 10:35

3 Answers3

1
<?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
    }
]
Progrock
  • 7,373
  • 1
  • 19
  • 25
0

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"];
    }
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • [ { count_of_invites: 5, user: "Rajesh", id: "53" }, { count_of_invites: 4, user: "Student", id: "45", student: null } ]This is what i get after encoding it to json.As the value doent sum up – Kiran JB Jun 18 '18 at 10:53
  • @KiranJB I have edited my answer, please, check it out. The mistake was that in the else I have used a student field instead of the user field. – Lajos Arpad Jun 18 '18 at 10:55
  • The count_of_invites shows the last data only.not the sum of all the value.my problem is to get the sum of values which has same key and in single occurence – Kiran JB Jun 18 '18 at 11:37
  • @Kiran can you please update your question then as I asked an hour ago. I'm not too keen or typing your whole array in manually. – Andreas Jun 18 '18 at 12:00
  • @Lajos Arpad .There were some editing to your mentioned code .But I've solve the problem .Thank you Arpad .It was a great help.I appreciate it .I'm posting the edited code . – Kiran JB Jun 18 '18 at 12:19
  • @KiranJB I was not aware that you are interested in getting the sum. However, I think my answer was pretty close to your needs, so if you think it was helpful, you might want to accept it, so future visitors to the page will know this is the correct answer. $output[$ids[$value["id"]]]["count_of_invites"] += $value["count_of_invites"]; would calculate the sum you need. – Lajos Arpad Jun 18 '18 at 13:17
0

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"];
        }
    }
Kiran JB
  • 1
  • 3