合并PHP关联数组

时间:2014-09-06 20:11:36

标签: php arrays sorting

我有多个arrays,我试图merge他们。想象一下以下代码;

$arr1[ 'a' ] = array( 'a', 'b', 'c' );
$arr2[ 'a' ] = array( 'd', 'e', 'f' );
$arr3[ 'a' ] = array( 'g', 'h', 'i' );

$arr1[ 'b' ] = array( 'a', 'b', 'c' );
$arr2[ 'b' ] = array( 'd', 'e', 'f' );
$arr3[ 'b' ] = array( 'g', 'h', 'i' );

$buf = array_merge( $arr1, $arr2, $arr3 );
print_r( $buf );

我期待的结果是;

Array
(
  [a] => Array
    (
      [ 0 ] => a
      [ 1 ] => b
      [ 2 ] => c
      [ 3 ] => d
      [ 4 ] => e
      [ 5 ] => f
      [ 6 ] => g
      [ 7 ] => h
      [ 8 ] => i
    )

  [b] => Array
    (
      [ 0 ] => a
      [ 1 ] => b
      [ 2 ] => c
      [ 3 ] => d
      [ 4 ] => e
      [ 5 ] => f
      [ 6 ] => g
      [ 7 ] => h
      [ 8 ] => i
    )
)

我尝试使用array_merge( )array_combine( )但没有成功。希望任何人都可以提供帮助。

4 个答案:

答案 0 :(得分:4)

使用:

$buf = array_merge_recursive($arr1, $arr2, $arr3);

答案 1 :(得分:2)

这样的事情:

<?php
$arr1[ 'a' ] = array( 'a', 'b', 'c' );
$arr2[ 'a' ] = array( 'd', 'e', 'f' );
$arr3[ 'a' ] = array( 'g', 'h', 'i' );

$arr1[ 'b' ] = array( 'a', 'b', 'c' );
$arr2[ 'b' ] = array( 'd', 'e', 'f' );
$arr3[ 'b' ] = array( 'g', 'h', 'i' );

$array = [
    'a' => array_merge($arr1['a'], $arr2['a'], $arr3['a']),
    'b' => array_merge($arr1['b'], $arr2['b'], $arr3['b'])
];

var_dump($array);

答案 2 :(得分:1)

array_merge()只能看到数组深入一层。您应该array_merge_recursive()使用this

$buf = array_merge_recursive( $arr1, $arr2, $arr3 );

答案 3 :(得分:0)

$ arr1 [&#39; a&#39; ] = array(&#39; a&#39;,&#39; b&#39;,&#39; c&#39;);

$ arr2 [&#39; a&#39; ] = array(&#39; d&#39;,&#39; e&#39;,&#39; f&#39;);

$ arr3 [&#39; a&#39; ] = array(&#39; g&#39;,&#39; h&#39;,&#39; i&#39;);

$ arr1 [&#39; b&#39; ] = array(&#39; a&#39;,&#39; b&#39;,&#39; c&#39;);

$ arr2 [&#39; b&#39; ] = array(&#39; d&#39;,&#39; e&#39;,&#39; f&#39;);

$ arr3 [&#39; b&#39; ] = array(&#39; g&#39;,&#39; h&#39;,&#39; i&#39;);

$ array = array(

'a' => array_merge($arr1['a'], $arr2['a'], $arr3['a']),
'b' => array_merge($arr1['b'], $arr2['b'], $arr3['b'])

);

的print_r($阵列);