本文实例总结了php常用数组array函数。分享给大家供大家参考,具体如下:
array_combine
功能:用一个数组的值作为新数组的键名,另一个数组的值作为新数组的值
案例:
<?php$a = array("one","two","three");$b = array("一","二","三");$c = array_combine($a,$b);print_r($c);/**结果*Array ( [one] => 一 [two] => 二 [three] => 三 )*/
array_chunk
功能:拆分数组成多个数组
<?php$input_array = array("a"=>"apple","b"=>"blue","c","d","e");echo "<pre>";print_r(array_chunk($input_array, 2));print_r(array_chunk($input_array, 2,True));echo "</pre>";/**结果Array( [0] => Array ( [0] => apple [1] => blue ) [1] => Array ( [0] => c [1] => d ) [2] => Array ( [0] => e ))Array( [0] => Array ( [a] => apple [b] => blue ) [1] => Array ( [0] => c [1] => d ) [2] => Array ( [2] => e ))*/
array_count_values
功能:统计数组中值出现的次数
<?php$input_array = array("a"=>"apple","b"=>"blue","c","d","e");echo "<pre>";print_r(array_count_values($input_array));echo "</pre>";/**结果Array( [apple] => 1 [blue] => 1 [c] => 1 [d] => 1 [e] => 1)*/
array_diff
功能:第一个数组中去掉第二个数组中有的数据,返回剩下的内容作为结果
<?php$array1 = array("a"=>"apple","b"=>"blue","c","d","e");$array2 = array("apple","c","d","f");$result = array_diff($array1, $array2);$result2 = array_diff($array2, $array1);echo "<pre>";print_r($result);//数组1中去掉数组2中剩下的print_r($result2);//数组2中去掉数组1中剩下的echo "</pre>";/**结果Array( [b] => blue [2] => e)Array( [3] => f)*/
array_map
功能:将回调函数执行到数组中
<?php//定义回调函数function cube($n){ return ($n*$n*$n);}$a = array(1,2,3,4,5);$b = array_map("cube",$a);echo "<pre>";print_r($b);echo "</pre>";/**结果Array( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125)*/
array_merge
功能:合并一个或多个数组
说明:如果后面有键名相同的会覆盖掉前面的内容,键名为数字的会添加到后面
<?php$array1 = array("color"=>"red",2,4);$array2 = array("a","b","color"=>"green","shape"=>"trapezoid",4);$result1 = array_merge($array1,$array2);$result2 = array_merge_recursive($array1,$array2);echo "<pre>";print_r($result1);print_r($result2);echo "</pre>";/**结果Array( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4)Array( [color] => Array ( [0] => red [1] => green ) [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4)*/
新闻热点
疑难解答