对数组的array_merge函数和+运算符比较迷惑,写了个小程序比较下发现了他们的不同。
特别是+运算符,他的意思是,将右边的数组单元(去重复)追加到左边数组的后面。
代码如下 |
复制代码 |
$arr1=array("a","b","c");
$arr2=array("c","d","e");
$myarray=array_merge($arr1,$arr2);
print_r($myarray);
$myarray=array_unique($myarray);
print_r($myarray);
?>
|
例
代码如下 |
复制代码 |
$array1=array(1, 2);//数组1
$array2=array(2, 3);//数组2
$array3=array_merge($array1, $array2);//合并数组;
$array3=array_unique($array3);//移除数组中重复的值
?>
|
例子
代码如下 |
复制代码 |
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
)
|
拆分数组 array_slice()
array_slice()函数将返回数组中的一部分,从键offset开始,到offset+length位置结束。其形式:
Php代码
1.array array_slice (array array, int offset[,int length])
array array_slice (array array, int offset[,int length])
offset 为正值时,拆分将从距数组开头的offset 位置开始;如果offset 为负值,则拆分从距数组末尾的offset 位置开始。如果省略了可选参数length,则拆分将从offset 开始,一直到数组的最后一个元素。如果给出了length 且为正数,则会在距数组开头的offset+length 位置结束。相反,如果给出了length且为负数,则在距数组开头的count(input_array)-|length|位置结束。考虑一个例子:
Php代码
代码如下 |
复制代码 |
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
$subset = array_slice($fruits, 3);
print_r($subset);
// output
// Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon )
?>
|
然后我们使用下负长度:
Php代码
代码如下 |
复制代码 |
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
$subset = array_slice($fruits, 2, -2);
print_r($subset);
// output
// Array ( [0] => Orange [1] => Pear [2] => Grape )
?>
|