標籤:php array 數組
//1 將key值大小替換
$arr = array(‘a‘ => 1, ‘b‘ => 2, ‘C‘ =>3, ‘D‘ => 4); $lower = array_change_key_case($arr, CASE_LOWER); $upper = array_change_key_case($arr, CASE_UPPER); //var_dump($lower); //var_dump($upper);
//2 將數組分割為$size個數組,hasKay為是否保留原來的key值
$arr2 = array(‘name‘ => ‘lixueyao‘, ‘age‘ => 24, ‘sex‘ => ‘f‘); $size = 2; $hasKey = true; $chunk = array_chunk($arr2, $size, $hasKey); //var_dump($chunk);
//3 可以將多維陣列中指定的key產生一個新數組,第3個參數,可以作為新數組的key值
$arr3s = array( array(‘name‘ => ‘lixueyao‘, ‘age‘ => 24, ‘sex‘ => ‘f‘), array(‘name‘ => ‘zhangsan‘, ‘age‘ => 25, ‘sex‘ => ‘m‘), array(‘name‘ => ‘lisi‘, ‘age‘ => 26, ‘sex‘ => ‘f‘) ); $column = array_column($arr3s, ‘age‘, ‘name‘); //print_r($column);
//4 合并倆個數組,形成的新數組中一個作為value,一個作為key
$arrCombineOne = array(‘one‘, ‘two‘, ‘three‘); $arrCombineTwo = array(‘1‘, ‘2‘, ‘3‘); $combine = array_combine($arrCombineTwo, $arrCombineOne); //print_r($combine);
//5 返回數組中value 出現的次數
$arrValue = array(‘c‘, ‘d‘, ‘a‘, ‘c‘, ‘v‘); $arrcnt = array_count_values($arrValue); //print_r($arrcnt);
//6 比較數組value 的差集 , one和two參數比較,在two數組中的不存在的就是差集 (用one和two去對比, one是被比較的數組)
//如果是多個數組進行比較則是3個數組的差集。(可以比較多個數組)
$arrDiffOne = array(‘a‘ => ‘red‘, ‘b‘ => ‘blue‘ , ‘c‘ => ‘black‘, ‘d‘ => ‘purple‘); $arrDiffTwo = array(‘a‘ => ‘red‘, ‘b‘ => ‘blue‘, ‘n‘ => ‘black‘,); $arrDiffThree = array(‘a‘ => ‘red‘, ‘f‘ => ‘hello‘, ‘c‘ => ‘black‘); $arrDiff = array_diff($arrDiffOne, $arrDiffTwo, $arrDiffThree); //print_r($arrDiff)
;
//7 比較數組的key 和 value(都相同),one是被比較的數組
//如果是3個數組去比較的話,可以先比較倆個數組,然後再用其他數組去比較前倆個數組的差集
$arrAssoc = array_diff_assoc($arrDiffOne, $arrDiffTwo, $arrDiffThree); //print_r($arrAssoc);
//8 比較數組的key值,原理同上
$a4 = array(‘d‘ =>‘name‘); $arrKey = array_diff_key($arrDiffOne, $arrDiffTwo, $arrDiffThree, $a4); //print_r($arrKey);
//9 比較數組,但是會比較key (自訂的函數不是很明白, one是被比較的
$uassocOne = array(‘name‘ => ‘zsy‘, ‘age‘=>24, ‘say‘ => ‘hello‘); $uassocTwo = array(‘name‘ => ‘lixueyao‘, ‘age‘ => 24); function myfunction($a , $b) { $res = null; if($a === $b) { $res = 0; } $res = ($a<$b) ? 1:-1; return $res; } $arrUassoc = array_diff_uassoc($uassocOne, $uassocTwo, ‘myfunction‘); print_r($arrUassoc);
//10 比較key
function myDiffKey($a,$b) { if ($a===$b) { return 0; } return ($a>$b)?1:-1; } $result=array_diff_ukey($uassocOne,$uassocTwo,"myDiffKey"); print_r($result);
php 數組方法總結--例子就是真理