在PHP中,数组合并主要有以下几种方式,每种方式都有其特定的用途和区别:
array_merge()
array_merge()
会重新索引,从0开始。php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
输出:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
array_merge_recursive()
示例:
$array1 = array("color" => array("favorite" => "red"), 5);
$array2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($array1, $array2);
print_r($result);
输出:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)
+
运算符php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
print_r($result);
输出:
Array
(
[0] => zero_a
[2] => two_a
[3] => three_a
[1] => one_b
[4] => four_b
)
array_replace()
php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$result = array_replace($base, $replacements, $replacements2);
print_r($result);
输出:
Array
(
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry
)
array_replace_recursive()
示例:
$base = array('citrus' => array("orange"), 'berries' => array("blackberry", "raspberry"));
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));
$result = array_replace_recursive($base, $replacements);
print_r($result);
输出:
Array
(
[citrus] => Array
(
[0] => pineapple
)
[berries] => Array
(
[0] => blueberry
[1] => raspberry
)
)
array_merge()
: 适合合并数组并重新索引数字键。array_merge_recursive()
: 适合递归合并数组,特别是多维数组。+
运算符: 适合保留第一个数组的值,忽略后续数组的相同键名。array_replace()
: 适合替换数组中的元素,保留数字键。array_replace_recursive()
: 适合递归替换数组中的元素,保留数字键。根据具体的需求选择合适的数组合并方式。