PHP[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

 

相关文章