如何将具有相同键的多个数组组合到一个数组中?

时间:2010-09-17 08:06:58

标签: php arrays merge multidimensional-array

我是php的新手。我需要一些帮助。 我有一个数组

Array ( [_] => Array ( [0] => [1] => )
        [123_] => Array ( [0] => 123 [1] => ) 
        [1234_] => Array ( [0] => 1234 [1] => )
      )
Array ( [_] => Array ( [0] => [1] => )
        [12345_] => Array ( [0] => 12345 [1] => ) 
        [1234_] => Array ( [0] => 1234 [1] => )
      )

所以......我的问题是我想要一个包含所有这些键和值的数组

Array ( [_] => Array ( [0] => [1] => )
        [123_] => Array ( [0] => 123 [1] => ) 
        [1234_] => Array ( [0] => 1234 [1] => )
        [_] => Array ( [0] => [1] => )
        [12345_] => Array ( [0] => 12345 [1] => ) 
        [1234_] => Array ( [0] => 1234 [1] => )
  )

会有重复的键和值..但我想将它们全部作为一个数组..任何帮助PLZ ..

3 个答案:

答案 0 :(得分:7)

可能。 PHP数组不能有两个相同的键。

答案 1 :(得分:1)

正如其他人所说,拥有重复密钥的单个阵列是不可能的。但是你可以构建一个数组数组:

<?php
$arr1 = array( '_' => Array ( '0' => '', '1' => ''),
             '123_' => Array ( '0' => 123, '1' => ''), 
             '1234_' => Array ( '0' => 1234, '1' => '')
);
$arr2 = array ( '_' => Array ( '0' => '', '1' => ''),
               '12345_' => Array ( '0' => 12345, '1' => ''), 
               '1234_' => Array ( '0' => 1234, '1' => '')
);
$result = array();
foreach( $arr1 as $key => $val) {
  $result[] = array('key'=>$key, 'value'=>$val);
}
foreach( $arr2 as $key => $val) {
  $result[] = array('key'=>$key, 'value'=>$val);
}
print_r($result);
?>

输出继电器:

Array
(
    [0] => Array
        (
            [key] => _
            [value] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [1] => Array
        (
            [key] => 123_
            [value] => Array
                (
                    [0] => 123
                    [1] =>
                )

        )

    [2] => Array
        (
            [key] => 1234_
            [value] => Array
                (
                    [0] => 1234
                    [1] =>
                )

        )

    [3] => Array
        (
            [key] => _
            [value] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [4] => Array
        (
            [key] => 12345_
            [value] => Array
                (
                    [0] => 12345
                    [1] =>
                )

        )

    [5] => Array
        (
            [key] => 1234_
            [value] => Array
                (
                    [0] => 1234
                    [1] =>
                )

        )

)

答案 2 :(得分:0)

看看PHP的array_merge()-function