Home  >  Article  >  php教程  >  php数组操作实例三

php数组操作实例三

WBOY
WBOYOriginal
2016-06-13 11:18:191070browse

本文章主要针对数组交集、判断键是否存在于数组中、合并两个数组、数据排序、增加数组,删除数组元素、随机抽取数组元素等实例。  

本文章主要针对数组交集、判断键是否存在于数组中、合并两个数组、数据排序、增加数组,删除数组元素、随机抽取数组元素等实例。
*/
$array1=array("a"=>"green","red","blue");
$array2=array("b"=>"green","yellow","red");
$result=array_intersect($array1,$array2);//计算交集并赋值
print_r($result);

//

$search_array=array('first'=>1,'second'=>4);   //定义数组
if(array_key_exists('first',$search_array))    //判断键是否存在于数组中
{
  echo "the 'first' element is in the array";    //输出相应信息
}

//

$ar1=array("color"=>array("favorite"=>"red"),5);
$ar2=array(10,"color"=>array("favorite"=>"green","blue"));
$result=array_merge_recursive($ar1,$ar2);   //合并两个数组返回一个结果数组
print_r($result);         //输出结果

//

$array1=array("color"=>"red",2,4);
$array2=array("a","b","color"=>"green","shape"=>"trapezoid",4);
$result=array_merge($array1,$array2);     //合并两个数组
print_r($result);          //输出结果内容

//

$ar1=array("10",100,100,"a");    //定义数组1
$ar2=array(1,3,"2",1);     //定义数组2
array_multisort($ar1,$ar2);    //排序2个数组
var_dump($ar1);      //打印排序后的结果
var_dump($ar2);      //打印排序后的结果

//
$stack=array("orange","banana","apple","rasp教程berry");  //定义一个数组
$fruit=array_pop($stack);        //最后一个元素出栈
print_r($stack);          //显示结果

//

$stack=array("orange", "banana");     //定义原始数组
array_push($stack,"apple","raspberry");    //执行压栈操作
print_r($stack);         //显示结果,将返回四个值

//

srand((float)microtime()*10000000);       //为随机数发生器播种
$input=array("neo","morpheus","trinity","cypher","tank");   //定义原始数组
$rand_keys=array_rand($input,2);       //随机挑选数组元素
print $input[$rand_keys[0]]."n";        //分别显示随机挑选的数组元素
print $input[$rand_keys[1]]."n";


Statement:
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