PHP中数组合并的两种方法

来源:互联网 发布:笛子模仿软件 编辑:程序博客网 时间:2024/06/06 01:59

1 使用array_merge();

例: 

<?php
error_reporting(E_ALL ^ E_NOTICE);
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");


$c = array_merge($a,$b);
echo "Union of \$a and \$b: \n";
var_dump($c);


?>

输出结果:Union of $a and $b: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" }

当键值相同时,$a中的键值替换了,


2 使用+

<?php
error_reporting(E_ALL ^ E_NOTICE);
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");


$c = $a+$b;
echo "Union of \$a and \$b: \n";
var_dump($c);


?>

返回结果:Union of $a and $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" }

当键值相同时,$b中的键值对替换了。

0 0
原创粉丝点击