开发者

How to merge arrays with same key and different value in PHP?

I have arrays similarly to these:

0 => Array ( [0] => Finance / Shopping / Food, [1] => 47 )            
1 => Array ( [0] => Finance / Shopping / Food, [1] => 25 )                 
2 => Array ( [0] => Finance / Shopping / Electronic, [1] => 190 ) 

I need to create one array with [0] as a key and [1] as value.

The tricky part is that if the [0] is same it add [1] to existing value.

So the result I want is:

array ([Finance / Shopping / Food]=> 72, [Finance / Shopping / Electronic] => 190);

than开发者_如何学运维ks


// array array_merge_values($base[, $merge[, ...]])
// Combines multiple array values based on key
//   (adding them together instead of the native array_merge using append)
//
// $base       - array to start off with
// $merge[...] - additional array(s) to include (and add their values) on to the base
function array_merge_values()
{
  $args = func_get_args();

  $result = $args[0];
  for ($_ = 1; $_ < count($args); $_++)
    foreach ($args[$_] as $key => $value)
    {
      if (array_key_exists($key,$result))
        $result[$key] += $value;
      else
        $result[$key] = $value;
    }
  return $result;
}

$array1 = Array('foo' => 5, 'bar' => 10, 'foobar' => 15);
$array2 = Array('foo' => 20,                             'foohbah' => 25);
$array3 = Array(            'bar' => 30);
var_dump(array_merge_values($array1,$array2,$array3));

Result:

array(4) {
  ["foo"]=>
  int(25)
  ["bar"]=>
  int(40)
  ["foobar"]=>
  int(15)
  ["foohbah"]=>
  int(25)
} 

That what you're looking for?


This should work:

$outArray = array()
foreach($superArray as $subArray) {
  if(array_key_exists($outArray,$subArray[0])) { 
    $outArray[$subArray[0]] += $subArray[1]; 
  } else { 
    $outArray[$subArray[0]] = $subArray[1]; 
  }
}


Well I don't know how big that array is or what a factor performance is. But this is very specific and I dare to recommend the naive straight forward procedural approach:

<?
$result = array();
foreach($arr as $a) {
   $result[$a[0]] += $result[$a[1]];
}
?>

this will generate some php warning, because the field isnt set yet so you probably need to do something like check if the key exists and if not set it the value, and if it is, add the value...

edit: well lets post this, this could look like

<?
$result = array();
foreach($arr as $a) {
   if(isset($result[$a[0]])) {
       $result[$a[0]] += $result[$a[1]];
   } else {
       $result[$a[0]] = $result[$a[1]];
   }
}
?>


You can use the "+" operand for the purpose.

$arr1 = array(
  'key' => '1',
);
$arr2 = array(
  'key' => '2',
);
die(var_dump($arr2 + $arr1));

RESULT:
array
  'key' => string '2' (length=1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜