想知道如何将一个数组的值添加到另一个数组中以节省我一遍又一遍地输入一个数组的值:
$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'
);
那么有什么可以将数组转换成字符串吗?我已经尝试了implode
和array_shift
,但我需要整个array()
而不仅仅是值..
答案 0 :(得分: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'));
答案 1 :(得分: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
)
答案 2 :(得分: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
)
答案 3 :(得分:0)
使用array_merge()
$array_1 = array_merge($array_main, array('[5]' => '5'));