php怎么合并两个数组?

PHPz
Release: 2020-09-05 13:35:13
Original
10740 people have browsed it

php怎么合并两个数组?

PHP合并两个或多个数组的方法

1、使用array_merge()函数

array_merge()函数可以用于将两个或多个数组合并为一个数组,例:

 "red", "1" => "green","2" => "yellow"); $y = array("3" => "blue", "2" => "yellow","1" => " orange"); $z = array_merge($x, $y); // $x 与 $y 的联合 var_dump($z); ?>
Copy after login

输出:

3.jpg

可以看出,array_merge()函数传递给数组键的数字索引在返回的数组中从零开始重新编号。

2、使用运算符“+”

PHP的数组运算符“+”可以用来联合两个(或多个数组)。

Copy after login

输出:

1.jpg

可以看出,第二个数组中只有第4个值包含在结果中,因为第二个数组的前三个元素具有和第一个数组元素相同的键。接下来让我们看看数组索引不匹配时数组联合运算符"+"的作用:

 "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); $z = $x + $y; // $x 与 $y 的联合 var_dump($z); ?>
Copy after login

输出:

2.jpg

可以看出:数组运算符“+”没有对结果中索引进行重新排序。

3、使用array_merge_recursive()函数

array_merge_recursive()函数可以把一个或多个数组合并为一个数组。

 "red", "1" => "green","2" => "yellow"); $y = array("3" => "blue", "2" => "yellow","1" => " orange"); $z = array_merge_recursive($x, $y); // $x 与 $y 的联合 var_dump($z); ?>
Copy after login

输出:

4.jpg

4、使用array_combine()函数

array_combine()函数会得到一个新数组,它由一组提交的键和对应的值组成。

示例代码:

$arr1 = array("A","B","C","D"); $arr2 = array("paul","itbsl","Golang","PHP"); $result = array_combine($arr1,$arr2); echo '
'; var_dump($result);
Copy after login

运行上面的代码,输出结果如下图所示:

4.png

更多相关知识,请访问PHP中文网!!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!