php怎么合并两个数组?

PHPz
Libérer: 2020-09-05 13:35:13
original
10781 Les gens l'ont consulté

php怎么合并两个数组?

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

1、使用array_merge()函数

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

<?php
header("content-type:text/html;charset=utf-8");
$x = array("0" => "red", "1" => "green","2" => "yellow"); 
$y = array("3" => "blue", "2" => "yellow","1" => " orange"); 
$z = array_merge($x, $y); // $x 与 $y 的联合
var_dump($z);
?>
Copier après la connexion

输出:

3.jpg

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

2、使用运算符“+”

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

<?php
header("content-type:text/html;charset=utf-8");
$x = array("red", "green","orange"); 
$y = array("red","blue","yellow","cyan"); 
$z = $x + $y; // $x 与 $y 的联合
var_dump($z);
?>
Copier après la connexion

输出:

1.jpg

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

<?php
header("content-type:text/html;charset=utf-8");
$x = array("a" => "red", "b" => "green"); 
$y = array("c" => "blue", "d" => "yellow"); 
$z = $x + $y; // $x 与 $y 的联合
var_dump($z);
?>
Copier après la connexion

输出:

2.jpg

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

3、使用array_merge_recursive()函数

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

<?php
 
header("content-type:text/html;charset=utf-8");
 
$x = array("0" => "red", "1" => "green","2" => "yellow"); 
 
$y = array("3" => "blue", "2" => "yellow","1" => " orange"); 
 
$z = array_merge_recursive($x, $y); // $x 与 $y 的联合
 
var_dump($z);
 
?>
Copier après la connexion

输出:

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 &#39;<pre class="brush:php;toolbar:false">&#39;;
var_dump($result);
Copier après la connexion

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

4.png

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

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!