在php教程中數(shù)組是種強(qiáng)大的數(shù)據(jù)類型,他可以做的事情很多,可以存儲(chǔ)不同的數(shù)據(jù)類型在一個(gè)數(shù)組中,下面我們列出了數(shù)組常用的操作,排序,鍵名對(duì)數(shù)組排序等做法。
使用函數(shù)array_keys(),得到數(shù)組中所有的鍵,參數(shù):數(shù)組
$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 )
使用函數(shù)array_values(),得到數(shù)組中所有的值,參數(shù):數(shù)組
$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 )
使用函數(shù)array_map(),使每個(gè)元素都調(diào)用一下自定義函數(shù),參數(shù):String類型函數(shù)名稱,數(shù)組
$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 )
使用函數(shù)array_merge(),把兩個(gè)數(shù)組合并成一個(gè),參數(shù):數(shù)組,數(shù)組
關(guān)聯(lián)數(shù)組合并時(shí),鍵相同的會(huì)被后面的數(shù)組覆蓋
索引數(shù)組合并時(shí),會(huì)連接在一起形成一個(gè)新的數(shù)組
$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 )
使用函數(shù)ksort(),按照鍵名進(jìn)行排序,注意沒(méi)有返回新的數(shù)組,還是原來(lái)的數(shù)組
$arr=array("2"=>"taoshihan2","1"=>"taoshihan1","3"=>"taoshihan3");
ksort($arr);
print_r($arr);
//Array ( [1] => taoshihan1 [2] => taoshihan2 [3] => taoshihan3 )
使用函數(shù)array_search(),搜索某個(gè)鍵值,返回對(duì)應(yīng)的鍵
$arr=array("2"=>"taoshihan2","1"=>"taoshihan1","3"=>"taoshihan3");
echo array_search("taoshihan1",$arr);
// 1