PHP写程序除了经常对字符串进行加工,还要经常对数组进行加工计算,所以了解你将会经常用到哪些数组函数
常用数组相关函数清单:
int count($array)
统计数组的元素个数
$arr = ['lmy', 7, 'abc', 'x' => 8];
echo count($arr); //4
array array_map($callback, $array)
用$callback处理$array的每一个元素
<?php
function cube ( $n )
{
return( $n * $n * $n );
}
$a = array( 1 , 2 , 3 , 4 , 5 );
$b = array_map ( "cube" , $a );
print_r ( $b );
?>
结果:Array
(
[0] => 1
[1] => 8
[2] => 27
[3] => 64
[4] => 125
)
string array_search
在数组中搜索给定的值,如果成功则返回相应的键名
<?php
$array = array( 0 => 'blue' , 1 => 'red' , 2 => 'green' , 3 => 'red' );
$key = array_search ( 'green' , $array ); // $key = 2;
$key = array_search ( 'red' , $array ); // $key = 1;
?>
-
number array_sum
计算数组中所有值的和
<?php
$a = array( 2 , 4 , 6 , 8 );
echo "sum(a) = " . array_sum ( $a ) . "\n" ;
$b = array( "a" => 1.2 , "b" => 2.3 , "c" => 3.4 );
echo "sum(b) = " . array_sum ( $b ) . "\n" ;
?>
结果:sum(a) = 20
sum(b) = 6.9
array array_merge($array1, $array2, [$array...])
合并数组
$arr1 = [1, 2, 3];
$arr2 = [4, 5];
print_r(array_merge($arr1, $arr2));
//结果:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
int array_push($array, $var)
向数组末尾追加一个新的元素
$arr = [1, 8];
array_push($arr, 77);
print_r($arr);
//结果如下:
Array
(
[0] => 1
[1] => 8
[2] => 77
)
array array_place
使用传递的数组替换第一个数组的元素
<?php
$base = array( "orange" , "banana" , "apple" , "raspberry" );
$replacements = array( 0 => "pineapple" , 4 => "cherry" );
$replacements2 = array( 0 => "grape" );
$basket = array_replace ( $base , $replacements , $replacements2 );
print_r ( $basket );
?>
结果
Array
(
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry
)
bool sort($array, $sortFlag = SORT_REGULAR)
对数组进行排序
$arr = [7, 8, 5, 1, 'xx' => 4];
sort($arr);
print_r($arr);
//结果如下:
Array
(
[0] => 1
[1] => 4
[2] => 5 //不保留索引
[3] => 7
[4] => 8
)
bool rsort(array &$array, int $sort_flags = SORT_REGULAR)
对数组逆向排序,其实就跟sort的结果相反sort是升序的,这个排序后是降序的
$arr = ['x', 'b', 'h'];
sort($arr);
print_r($arr); //字母升序: b h x
rsort($arr);
print_r($arr); //字母降序: x h b
bool asort(array &$array, int $sort_flags = SORT_REGULAR)
对数组进行排序并保留key
$arr = [7, 8, 5, 1, 'xx' => 4];
asort($arr);
print_r($arr);
//结果如下:
Array
(
[0] => 1
[xx] => 4 //保留了索引
[2] => 5
[3] => 7
[4] => 8
)
这些都是使用率比较高的,其余的请参考php手册