简体   繁体   English

合并2个数组并合并数字键的结果

[英]Merge 2 arrays and combine results of numerical keys

I have 2 arrays in which I wish to merge/group together by each numerical key. 我有2个数组,希望通过每个数字键将它们合并/分组在一起。 eg 例如

Array1
(
    [2009] => 131
    [2008] => 940
    [2007] => 176
    [2006] => 1
)
Array2
(
    [2008] => 9
    [2007] => 3
)

I would like the output to be: 我希望输出为:

Array (
    [2009] => 131
    [2008] => Array (
                     [0]=>940
                     [1]=>9
                    )
    [2007] => Array (
                     [0]=>176
                     [1]=>3
                    )
    [2006] => 1
)

How on earth do I achieve this? 我到底该如何实现? I have tried array_merge but I lose my keys and they don't get grouped. 我尝试了array_merge,但是我丢失了密钥,并且它们没有分组。

If I see that right you only want those key to hold an array, that reference more than a single value. 如果我看对了,您只希望这些键保存一个数组,那么该引用不仅仅是一个值。 The other keys should still refer to scalar values... 其他键仍应引用标量值...

So you need a two step strategy: 因此,您需要采取两步策略:

// 1.) turn _all keys into arrays
foreach (array($input1,$input2) as $array)
    foreach ($array1 as $key=>$val)
        $output[$key][]=$val;
// 2.) reconvert elements with single entry to a scalar value again
foreach ($output as $key=>$candidate)
    if (1==count($candidate))
        $output[$key]=$candidate[0];
// test output
print_r($output);

Why don't you just write a method to merge them? 您为什么不编写一种合并它们的方法?

/**
Merge original_array with new_array
@param array original_array
@param array new_array
*/
function merge_array($original_array, $new_array)
{
    $merged_array = array();
    if(is_array($original_array) && is_array($new_array))
    {
        foreach($original_array as $key => $value)
        {
            $merged_row[] = $value;
            if(isset($new_array[$key]))
            {
                $merged_row[] = $new_array[$key];
            }
            $merged_array[$key] = $merged_row;
        }
    } else $merged_array = $original_array;
    return $merged_array;
}

Just unit tested this. 只是单元测试了这一点。 It should union the arrays. 它应该合并数组。 Mind you it could be improved in terms of performance. 请注意,可以在性能方面进行改进。 Items without an associative key will be grouped into key '0'. 没有关联密钥的项目将被分组为密钥“ 0”。

   public function merge(&$ar, $ar2) {
      foreach ($ar as $k => $v) {
         if (isset($ar2[$k])) {
            $ar[$k] = array_merge(array($ar[$k]), array($ar2[$k]));
         }
      }

      foreach ($ar2 as $k => $v) {
         if (!isset($ar[$k])) {
            $ar[$k] = $ar2[$k];
         }
      }    
    }

The unit test: 单元测试:

public static function test_merge() {
      $ar1 = array(45, 'a' => 44, 'dog' => array(1), 'cat' => 3);
      s($ar1, array(2, 'dog' => 2, 'cat' => 4, 'stuff' => 4.3));
      print_r($ar1);
}

The result: 结果:

IArray
(
    [0] => Array
        (
            [0] => 45
            [1] => 2
        )

    [a] => 44
    [dog] => Array
        (
            [0] => Array
                (
                    [0] => 1
                )

            [1] => 2
        )

    [cat] => Array
        (
            [0] => 3
            [1] => 4
        )

    [stuff] => 4.3
)
<?php
$arrOne = array( 2009 => 131,  2008 => 940,  2007 => 176,  2006 => 1);
$arrTwo = array( 2008 => 9, 2007=> 3, 2011 => 67);
$output = array();


foreach($arrOne as $key=>$value){
  if(isset($arrTwo[$key])){
    $output[$key][] = $value;
    $output[$key][] = $arrTwo[$key];
  }
  else{
    $output[$key] = $value;
  }
}

$output += $arrTwo;    // To consider keys that were absent in $arrOne 
print_r($output);

?>

Check the output in http://codepad.org/FrIlKRqk http://codepad.org/FrIlKRqk中检查输出

And the result 结果

Array
(
[2009] => 131
[2008] => Array
    (
        [0] => 940
        [1] => 9
    )

[2007] => Array
    (
        [0] => 176
        [1] => 3
    )

[2006] => 1
[2011] => 67
)

Both arrays use the same keys, so you could do something simple like this (only works on one level though): 这两个数组使用相同的键,因此您可以执行以下简单操作(尽管仅适用于一个级别):

foreach ($array2 as $key => $value)
{
    $array1[$key][] = $value
}

Update: 更新:

$array3 = array()
foreach ($array1 as $key => $value)
{
    $array3[$key][] = $value
}
foreach ($array2 as $key => $value)
{
    $array3[$key][] = $value
}

probaly something like that? 大概是这样的吗? If you run such a loop for each Array (array1, array2,…) 如果为每个数组(array1,array2等)运行这样的循环

$list = array()

foreach( $array1 as $key => $value ){
    if( !array_key_exist( $key, $array) ){
        $list[$key] = $value
    } else if( !is_array( $list[$key] ) ) {
        $list[$key] = array(list[$key])
    } else {
        array_push( $list[$key], $value );
    }
}

nb.: the code is not tested… nb .:该代码未经过测试…

Try: 尝试:

foreach ($your_array as $key => $value)
    $array_new[$key][] = $value;
print_r($array_new);

I see much answers but I dont find them usable so Im adding my own 我看到了很多答案,但我发现它们不可用,所以我添加了自己的答案

function merge(){
    $args = func_get_args();
    $new = array();
    foreach($args as $arg){
        foreach($arg as $key => $item){
            if(!isset($new[$key])){
                $new[$key] = $item;
            }else if (!is_array($new[$key)){
                $new[$key] = array($new[$key],$item);
            }else{
                $new[$key][] = $item;
            }
        }
    }
    return $new;
}

You can put in unlimited arguments :) 您可以输入无限的参数:)

I eventually found this function that helped me. 我最终找到了对我有帮助的功能。 Thank you everyone for your input. 谢谢大家的投入。

function merge_common_keys()
{
    $arr  = func_get_args();
    $num  = func_num_args();
    $keys = array();
    $i    = 0;
    for ($i = 0; $i < $num; ++$i) {
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys   = array_unique($keys);
    $merged = array();
    foreach ($keys as $key) {
        $merged[$key] = array();
        for ($i = 0; $i < $num; ++$i) {
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM