如何在PHP中将数组值添加到另一个数组?

时间:2012-03-07 09:22:45

标签: php arrays multidimensional-array for-loop foreach

我有两个值及其键的数组...
第一个数组

    Array
    (
    [0] => Array
        (
            [10] => A1
            [11] => A2
        )

    [1] => Array
        (
            [12] => B1
            [13] => B2
        )

)

第二个数组

Array
(
  [1] => Z1
  [2] => Z2
)

我想将这两个数组分组到一个数组中。我的意思是数组格式应该是:

Array
(
[0] => Array
    (
        [1] => Z1
        [10] => A1
        [11] => A2
    )

[1] => Array
    (
        [2] => Z2
        [12] => B1
        [13] => B2
    )
 )

我尝试使用array_push但是将整个数组添加到[0]位置或第二个数组中的[2]位置。

任何人都有任何想法?

1 个答案:

答案 0 :(得分:1)

你可以试试这段代码

$arrOne = array(
    0 => array(
        10 => 'A1',
        11 => 'A2'
    ),
    1 => array(
        12 => 'B1',
        13 => 'B2'
    )
);

$arrTwo = array(
    1 => 'Z1',
    2 => 'Z2'
);
$arrcountone = count($arrOne);
$arrcounttwo = count($arrTwo);
$i=0;
foreach ($arrOne as $key1 => $value1) {
    $i++;$k=0;
    foreach ($arrTwo as $key => $value) {
        $k++;
        if($i == $k){
            $arrOne[$key1][$key] = $value;
        }
    }
}

var_dump($arrOne)给出了

 array
      0 => 
        array
          1 => string 'Z1' (length=2)
          10 => string 'A1' (length=2)
          11 => string 'A2' (length=2)
      1 => 
        array
          2 => string 'Z2' (length=2)
          12 => string 'B1' (length=2)
          13 => string 'B2' (length=2)