在PHP中合并二维数组

时间:2016-09-21 09:00:10

标签: php arrays array-merge

很长一段时间不能解决smth看起来像非常简单的问题...我想合并一个二维数组。 例子:

$arr1 = {
  [532] =
  {
    [0] = "11"
    [1] = "12"
  }
  [273] =
  {
    [0] = "99"
  }
}
$arr2 = {
  [532] =
  {
    [0] = "11"
    [1] = "13"
  }
}

合并的结果应该是,公共键上的映射,与该数组完全相同:

$result = {
  [532] =
  {
     [0] =
     {      
        [0] = "11"
        [1] = "12"
     }
     [1] =
     {
        [0] = "11"
        [1] = "13"
     }
  }
  [273]
     [0] =
     {      
        [0] = "99"
     }
     [1] =
     {

     }
}

我尝试这样的话:

    $result = $arr1;
    foreach ($arr2 as $key => $value) {
        $result[$key] = isset($result[$key]) ? array_merge([$result[$key]], [$value]) : [$value];
    }

但是如果$ arr2为空则它不起作用:(

2 个答案:

答案 0 :(得分:1)

可能是这样的

 $arr1 = {
      [532] =
      {
        [0] = "11"
        [1] = "12"
      }
      [273] =
      {
        [0] = "99"
      }
    }
    $arr2 = {
      [532] =
      {
        [0] = "11"
        [1] = "13"
      }
    }

   $newarray = array();
   foreach ($arr1 as $key => $value) {
      $cu = $arr1[$key];

      $newarray[$key][] = $cu;

      if(!isset($arr2[$key])) {
            $newarray[$key][] = array();
       }
       else {
         $newarray[$key][] = $arr2[$key];
       }
   }

foreach ($arr2 as $key => $value) {
          if(!isset($newarray[$key])) {
             $newarray[$key][] = $arr2[$key]; 
          }
       }

答案 1 :(得分:1)

对于第二次数组检查,您需要使用array_merge()数组或不使用数组:

示例:

<?php
$arr1 = array('532'=>array('11','12'),'273'=>array('99'));
$arr2 = array('532'=>array('11','13'));

$newArr = array();
foreach ($arr1 as $key => $value) {
   if(isset($arr2[$key])){
      $newArr[$key][] = array_merge($value,$arr2[$key]);      
   }
   else{
      $newArr[$key] = $value;
   }
}
echo "<pre>";
print_r($newArr);
?>

<强>结果:

Array
(
    [532] => Array
        (
            [0] => Array
                (
                    [0] => 11
                    [1] => 12
                    [2] => 11
                    [3] => 13
                )

        )

    [273] => Array
        (
            [0] => 99
        )

)

此外,如果你想合并两个相同的索引,你可以使用template <int W> void bar(); 这样的东西:

#include <iostream>

template <int T>
class Testclass {
    public:
    void foo(void) {
        std::cout << T << std::endl;
    }

    template <int U>
    void bar(void) {
        std::cout << T << " " << U << std::endl;
    }
};

template <int W>
void bar();

template <int V>
void testfunction( void ) {
    Testclass<V> otherTestObj;
    otherTestObj.foo();
    otherTestObj.bar<4>();
}

int main() {
    Testclass<1> testobject;
    testobject.foo();
    testobject.bar<2>();
    testfunction<3>();

    return 0;
}

<强>结果:

{{1}}

请注意, ist脚本,会根据您的需要为您提供唯一索引的结果。 第二个脚本将在一个数组中为您提供所有值。