以下为学习孔祥盛主编的《PHP编程基础与实例教程》(第二版)所做的笔记。
数组集合运算函数
1. array_merge() 函数
程序:
1 <?php 2 $array1 = array("color"=>"red",2,4); 3 $array2 = array("a","b","color"=>"green","shape"=>"trapezoid",4); 4 $result = array_merge($array1,$array2); //并集 5 print_r($result); 6 //Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 ) 7 ?>
输出:
Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 )
2. array_diff() 函数
程序:
1 <?php 2 $array1 = array("color"=>"red",2,4); 3 $array2 = array("color"=>"red",2); 4 $result = array_diff($array1,$array2); //值的差集 5 print_r($result); //Array ( [1] => 4 ) 6 ?>
输出:
Array ( [1] => 4 )
3. array_intersect() 函数
程序:
1 <?php 2 $array1 = array("color"=>"red",2,4); 3 $array2 = array("color"=>"red",2); 4 $result = array_intersect($array1,$array2); //值的交集 5 print_r($result); //Array ( [color] => red [0] => 2 ) 6 ?>
输出:
Array ( [color] => red [0] => 2 )
4. array_diff_assoc() 函数
程序:
1 <?php 2 $array1 = array("a"=>"apple",'c'=>"cat",1,2); 3 $array2 = array("b"=>"apple",'c'=>'cat',"1"); 4 $result = array_diff_assoc($array1,$array2); //差集 5 print_r($result); //Array ( [a] => apple [1] => 2 ) 6 ?>
输出:
Array ( [a] => apple [1] => 2 )
5. array_intersect_assoc() 函数
程序:
1 <?php 2 $array1 = array("a"=>"apple",'c'=>"cat",1,2); 3 $array2 = array("b"=>"apple",'c'=>'cat',"1"); 4 $result = array_intersect_assoc($array1,$array2); //交集 5 print_r($result); //Array ( [c] => cat [0] => 1 ) 6 ?>
输出:
Array ( [c] => cat [0] => 1 )
6. array_diff_key() 函数
程序:
1 <?php 2 $array1 = array("a"=>"apple",1,"c"=>"cat",2); 3 $array2 = array("a"=>"banana","c"=>'cat',"1"); 4 $result = array_diff_key($array1,$array2); //键的差集 5 print_r($result); //Array ( [1] => 2 ) 6 ?>
输出:
Array ( [1] => 2 )
7. array_intersect_key() 函数
程序:
1 <?php 2 $array1 = array("a"=>"apple",'c'=>"cat",2); 3 $array2 = array("a"=>"banana",'c'=>'cat',"1"); 4 $result = array_intersect_key($array1,$array2); //键的交集 5 print_r($result); //Array ( [a] => apple [c] => cat [0] => 2 ) 6 ?>
输出:
Array ( [a] => apple [c] => cat [0] => 2 )