PHP中Array相關函數簡介_php技巧

來源:互聯網
上載者:User

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.