Matt Toner Matt Toner - 1 month ago 5
MySQL Question

PHP Adding Values With The Same ID's

Here's another PHP one for you all!

I have two arrays coming from two tables that have the same columns name but different values. I have created a query that call on both tables to dump the data into arrays. The values I get are: -

Array {
[0] {
[id] => 23,
[count] => 300
},
[1] {
[id] => 43,
[count] => 400
}
}


and

Array {
[0] {
[id] => 43,
[count] => 200
},
[1] {
[id] => 78,
[count] => 55
}
}


What I want to do is this: -

Array {
[0] {
[id] => 23,
[count] => 300
},
[1] {
[id] => 43,
[count] => 600 <---- Notice how this has been added together
},
[2] {
[id] => 78,
[count] => 55
}
}


How would I go about doing this?

Answer

array_merge might seem like a good option at first but is really not as it does not merge numeric keys but rather just appends them.

The easiest would be to write your own function for this merge.

Would look something like this:

function merge_array($first, $second)
{
    $result = array();
    append_array($result, $first);
    append_array($result, $second);

    return $result;
}

function append_array(&$result, $array)
{
    foreach($array as $entry){
        $index = get_element_index($result, $entry);
        if($index < 0){
            // Add as normal
            $result[] = $entry;
        }else{
            $result[$index]['count'] = $result[$index]['count'] + $entry['count'];
        }

    }
}

function get_element_index($array, $element)
{
    for($i = 0; $i < count($array); $i++){
        if($entry['id'] == $element['id']){
            return $i;
        }
    }
    return -1;
}