Question

I am having following two-dimensional array as follows..

array(
0 => array(
    0 => 'India',
    1 => '91'
),
1 => array(
    0 => 'Australia',
    1 => '1'
),
2 => array(
    0 => 'India',
    1 => '20'
),
3 => array(
    0 => 'Iraq',
    1 => '10'
),
4 => array(
    0 => 'Australia',
    1 => '3'
),
    5 => array(
    0 => 'Kuweit',
    1 => '14'
)
)

I want to take same inner array values if any exist and merge so that should be added.. So i want to get that array into following array.

  array(
 0 => array(
   0 => 'India',
   1 => 111
 ),
 1 => array(
   0 => 'Australia',
   1 => 4
 ),
 2 => array(
   0 => 'Iraq',
   1 => 10
 ),
 3 => array(
   0 => 'Kuweit',
   1 => 14
 )
)

How to get this array?

Was it helpful?

Solution

knittl's answer is more terse, but you could follow the same startegy like this:

// $in = source array in your question ... 

/* collect the totals */
$collect = array();
foreach ($in as $item)
{
    if (array_key_exists($item[0], $collect))
    {
        $collect[$item[0]] += $item[1];
    }
    else
    {
        $collect[$item[0]] = (int) $item[1];
    }
}

/* repackage the result */
$out = array();
foreach ($collect as $key => $value)
{
    $out[] = array($key, $value);
}

OTHER TIPS

I would iterate over the array and put everything into a new (temporary) associative array. In that temporary array I would use the (identifying) name as the key and additional information as the value. That way you have no duplicates at all.

During your iteration you can call array_key_exists to determine wether or not the name is already known in your temporary array, and if so you can store the sum of both the numbers in your temporary array.

Example (not validated; given that your first array is stored in $inputArray)

<?php

$mergedArray = array();

foreach($inputArray as $child) {

    list($key, $value) = $child;

    if(array_key_exists($key, $mergedArray) {
        $mergedArray[$key] += $child;
    } else {
        $mergedArray[$key] = $child;
    }

}

Iterate over the array, transform it into an associative array (using the country name as the key), and then transform it back to your numerically indexed array.

This can be nicely done with e.g. array_reduce and foreach:

$array = array(...);
$array = array_reduce($array, function(&$result, $item) {
    @$result[$item[0]] += $item[1]; // $result[$item[0]] might not exist, suppress error and auto-init to zero.
    // cleaner (less hackish) code: if(!isset($result[$item[0]])) $result[$item[0]] = 0;
  }, array());
// and transform back:
$newarray = array();
foreach($array as $k => $v) {
  $newarray[] = array($k, $v);
}

Runtime complexity should be O(n) (you only iterate twice)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top