PHP中Array关于数组的用法

使用函数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

 

posted @ 2016-12-24 17:16  鼎峰Bruce  阅读(336)  评论(0编辑  收藏  举报