0

我有以下二维数组,如下所示..

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'
)
)

如果存在任何内部数组值,我想采用相同的内部数组值并合并,以便添加。所以我想将该数组放入以下数组。

  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
 )
)

如何获得这个数组?

4

3 回答 3

1

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;
    }

}
于 2012-07-28T09:53:34.473 回答
1

遍历数组,将其转换为关联数组(使用国家名称作为键),然后将其转换回您的数字索引数组。

这可以用 egarray_reduce和很好地完成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);
}

运行时复杂度应该是 O(n) (你只迭代两次)

于 2012-07-28T10:07:41.420 回答
1

knittl 的回答更简洁,但你可以像这样遵循同样的策略:

// $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);
}
于 2012-07-28T10:43:52.667 回答