PHP中Array相关函数简介
程序员文章站
2024-04-02 15:32:40
使用函数array_keys(),得到数组中所有的键,参数:数组
$arr=array();
$arr['one']="one";
$arr['two']="...
使用函数array_keys(),得到数组中所有的键,参数:数组
$arr=array(); $arr['one']="one"; $arr['two']="two"; $arr['three']="three"; $newarr=array_keys($arr); print_r($newarr); //array ( [0] => one [1] => two [2] => three )
使用函数array_values(),得到数组中所有的值,参数:数组
$arr=array(); $arr[20]="one"; $arr[30]="two"; $arr[40]="three"; $newarr=array_values($arr); print_r($newarr); //array ( [0] => one [1] => two [2] => three )
使用函数array_map(),使每个元素都调用一下自定义函数,参数:string类型函数名称,数组
$arr=array(); $arr[0]="one"; $arr[1]="two"; $arr[2]="three"; function test($v){ return $v." hello"; } $newarr=array_map("test",$arr); print_r($newarr); //array ( [0] => one hello [1] => two hello [2] => three hello )
使用函数array_merge(),把两个数组合并成一个,参数:数组,数组
关联数组合并时,键相同的会被后面的数组覆盖
索引数组合并时,会连接在一起形成一个新的数组
$arr=array(); $arr[0]="one"; $arr[1]="two"; $arr[2]="three"; $arr1=array(); $arr[3]="taoshihan1"; $arr[4]="taoshihan2"; $arr[5]="taoshihan3"; $newarr=array_merge($arr,$arr1); print_r($newarr); //array ( [0] => one [1] => two [2] => three [3] => taoshihan1 [4] => taoshihan2 [5] => taoshihan3 ) $arr=array("one","two","three"); $arr1=array("4","5","6"); $newarr=array_merge($arr,$arr1); print_r($newarr); //array ( [0] => one [1] => two [2] => three [3] => 4 [4] => 5 [5] => 6 )
使用函数ksort(),按照键名进行排序,注意没有返回新的数组,还是原来的数组
$arr=array("2"=>"taoshihan2","1"=>"taoshihan1","3"=>"taoshihan3"); ksort($arr); print_r($arr); //array ( [1] => taoshihan1 [2] => taoshihan2 [3] => taoshihan3 )
使用函数array_search(),搜索某个键值,返回对应的键
$arr=array("2"=>"taoshihan2","1"=>"taoshihan1","3"=>"taoshihan3"); echo array_search("taoshihan1",$arr); // 1