Home > php教程 > php手册 > body text

PHP中array_merge合并两个数组的程序

WBOY
Release: 2016-06-13 10:15:46
Original
1198 people have browsed it

合并数据在php中我们利用array_merge()函数来实现,array_merge() 函数把两个或多个数组合并为一个数组。 如果键名有重复,该键的键值为最后一个键名对应的值(后面的覆盖前面的)。如果数组是数字索引的,则键名会以连续方式重新索引。

 代码如下 复制代码

 


echo "rn第一种情况rn";
$a=array(1,2,3,4,5,6);
$b=array(7,8,9);
 
$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);
 
 
echo "rn第二种情况rn";
$a=array('a','b','c','d','e','f');
$b=array('a','x','y');
 
$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);
 
 
echo "rn第三种情况rn";
 
$a=array(
 1=>'a',
 2=>'b',
 3=>'c',
 4=>'d',
 5=>'e',
 6=>'f');
$b=array(
 1=>'a',
 7=>'x',
 8=>'y');
 
$c=array_merge ($a,$b);
print_r($c);
$c=$a+$b;
print_r($c);
$c=$b+$a;
print_r($c);
?>

结果如下:

第一种情况
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [0] => 7
    [1] => 8
    [2] => 9
    [3] => 4
    [4] => 5
    [5] => 6
)
 
第二种情况
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => a
    [7] => x
    [8] => y
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)
Array
(
    [0] => a
    [1] => x
    [2] => y
    [3] => d
    [4] => e
    [5] => f
)
 
第三种情况
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => a
    [7] => x
    [8] => y
)
Array
(
    [1] => a
    [2] => b
    [3] => c
    [4] => d
    [5] => e
    [6] => f
    [7] => x
    [8] => y
)
Array
(
    [1] => a
    [7] => x
    [8] => y
    [2] => b
    [3] => c
    [4] => d
    [5] => e
    [6] => f
)

1)键名

为数字时,array_merge()不会覆盖掉原来的值,但+合并数组则会把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉(不是覆盖)

2)键名为字符时,+仍然把最先出现的值作为最终结果返回,而把后面的数组拥有相同键名的那些值“抛弃”掉,但array_merge()此时会覆盖掉前面相同键名的值


注释:如果仅仅向 array_merge() 函数输入了一个数组,且键名是整数,则该函数将返回带有整数键名的新数组,其键名以 0 开始进行重新索引

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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template