<?php
$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);
?>
例
代碼如下 復制代碼
<?php
$array1=array(1, 2);//數組1
$array2=array(2, 3);//數組2
$array3=array_merge($array1, $array2);//合並數組;
$array3=array_unique($array3);//移除數組中重復的值
?>
例子
代碼如下 復制代碼<?php
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代碼
代碼如下 復制代碼<?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代碼
代碼如下 復制代碼<?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 )
?>