3

想知道如何将一个数组的值添加到另一个数组中,以节省我一遍又一遍地键入一个数组的值:

$array_main = array(
    '[1]' => '1',
    '[2]' => '2',
    '[3]' => '3',
    '[4]' => '4'
);

$array_1 = array( $array_main, '[5]' => '5' );

由此推断:

$array_1 = array(
    array(
        '[1]' => '1',
        '[2]' => '2',
        '[3]' => '3',
        '[4]' => '4'
    ),
    '[5]' => '5'
);

但我想要:

$array_1 = array(
    '[1]' => '1',
    '[2]' => '2',
    '[3]' => '3',
    '[4]' => '4',
    '[5]' => '5'
);

那么有什么东西可以把数组变成字符串吗?我试过了implodearray_shift但我需要的array()不仅仅是价值观。

4

4 回答 4

3

最快的方法是简单地使用单个数组,如下所示,

$array_main = array(
    '[1]' => '1',
    '[2]' => '2',
    '[3]' => '3',
    '[4]' => '4'
);
$array1 = $array_main;
$array1['[5]'] = '5';

虽然如果对新数组的特定要求使用array_merge

$array1 = array_merge($array_main,array('[5]' => '5'));
于 2013-05-12T13:03:09.530 回答
3
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

http://php.net/manual/en/function.array-merge.php

于 2013-05-12T13:05:33.817 回答
0

您可以使用合并数组(不只是想添加一个额外的值)来合并两个数组:

<?php
    $array1 = array("0" => "0", "1" => "1");
    $array2 = array("a" => "a", "b" => "b");
    print_r( array_merge($array1, $array2 );
?>

印刷:

Array
(
    [0] => 0
    [1] => 1
    [a] => a
    [b] => b
)
于 2013-05-12T13:07:27.660 回答
0

采用array_merge()

$array_1 = array_merge($array_main, array('[5]' => '5'));
于 2013-05-12T13:10:08.357 回答