php合并数组的方法有:array_merge()合并多个数组、array_merge_recursive()递归合并(合并子数组),如果要保留键,使用array_merge_recursive()并启用第二个参数true。
PHP 中合并数组
合并两个数组
合并两个数组的最简单方法是使用 array_merge() 函数,它将两个或多个数组合并并返回一个新的数组。
$arr1 = ["a", "b", "c"];
$arr2 = [1, 2, 3];
$mergedArr = array_merge($arr1, $arr2);
// 结果:["a", "b", "c", 1, 2, 3]
合并多个数组
要合并多个数组,可以多次调用 array_merge() 函数或使用 array_merge_recursive() 函数。
$arr1 = ["a", "b", "c"];
$arr2 = [1, 2, 3];
$arr3 = ["foo", "bar", "baz"];
$mergedArr = array_merge($arr1, $arr2, $arr3);
// 结果:["a", "b", "c", 1, 2, 3, "foo", "bar", "baz"]
递归合并数组(合并子数组)
array_merge_recursive() 函数类似于 array_merge(),但它对数组进行递归合并,这意味着它会深入每个子数组并合并子数组中的键值对。
$arr1 = ["a" => "apple", "b" => ["c" => "cat", "d" => "dog"]];
$arr2 = ["a" => "banana", "b" => ["e" => "elephant"]];
$mergedArr = array_merge_recursive($arr1, $arr2);
// 结果:["a" => "banana", "b" => ["c" => "cat", "d" => "dog", "e" => "elephant"]]
合并数组并保留键
默认情况下,array_merge() 会覆盖相同的键。如果要保留键,可以使用 array_merge_recursive() 并启用 true 作为第二个参数。
$arr1 = ["a" => "apple", "b" => "banana"];
$arr2 = ["a" => "orange", "c" => "cat"];
$mergedArr = array_merge_recursive($arr1, $arr2, true);
// 结果:["a" => ["apple", "orange"], "b" => "banana", "c" => "cat"]
以上就是php中数组如何合并的详细内容,更多请关注编程网其它相关文章!