PHP 重回基礎(Array相關函式)

2022-01-30 21:34:43 字數 2039 閱讀 6119

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

)$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

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 使用函式ar...

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 ...

php函式系列 array函式相關一

1 array 建立陣列 arr array 建立乙個空陣列 2 array change key case array,case 將陣列中的所有鍵更改為大寫或者小寫 arr array bill 20 steve 56 mark 31 print r array change key case a...