PHP常用数组函数
PHP常用的数组函数
一、数组排序函数
1.sort(); 以升序对数组排序。
1 <?php 2 $color=array('green','red','yellow','black','white');
3 sort($color);
4 print_r($color);
5 ?>
结果输出:
Array
(
[0] => black
[1] => green
[2] => red
[3] => white
[4] => yellow
)
备注:按升序对数组进行排序
2.rsort(); 以降序对数组排序
1 <?php 2 $color=array('green','red','yellow','black','white'); 3 rsort($color); 4 print_r($color); 5 ?> 结果输出:
Array
(
[0] => yellow
[1] => white
[2] => red
[3] => green
[4] => black
)
备注:按降序对数组进行排序
3.ksort() ; 按照键名对关联数组进行升序排序。
1 <?php 2 $arr = ['c'=>'apple','f'=>'tree','a'=>'father','s'=>'teacher','g'=>'student',];
3 ksort($arr);
4 print_r($arr);
5 ?>
结果输出:
Array
(
[a] => father
[c] => apple
[f] => tree
[g] => student
[s] => teacher
)
备注:按键名升序排序
4.krsort() 函数对关联数组按照键名进行降序排序。
1 <?php 2 $arr = ['c'=>'apple','f'=>'tree','a'=>'father','s'=>'teacher','g'=>'student',];
3 krsort($arr);
4 print_r($arr);
5 ?>
结果输出:
Array
(
[s] => teacher
[g] => student
[f] => tree
[c] => apple
[a] => father
)
备注:按键名降序排序
5.asort(); 按照键值对关联数组进行升序排序。
1 <?php 2 $arr=['c'=>'apple','f'=>'tree','a'=>'father','s'=>'teacher','g'=>'student',];
3 asort($arr);
4 print_r($arr);
5 ?>
结果输出:
Array
(
[c] => apple
[a] => father
[g] => student
[s] => teacher
[f] => tree
)
备注:按值升序排序
6.arsort(); 按照键值对关联数组进行降序排序。
1 <?php
2 $arr=['c'=>'apple', 'f'=>'tree', 'a'=>'father', 's'=>'teacher', 'g'=>'student',];
3 arsort($arr);
4 print_r($arr);
5 ?>
结果输出:
Array
(
[s] => teacher
[g] => student
[f] => tree
[c] => apple
[a] => father
)
备注:按值降序排序
7.array_muiltsort(); 对多个数组或多维数组进行排序。
array_multisort ( array &$array1
[, mixed $array1_sort_order
= SORT_ASC [, mixed $array1_sort_flags
= SORT_REGULAR [, mixed $...
]]] )
<?php $arr4 = [ [1,2,3,4,5], ['a'=>'father','f'=>'before','d'=>'apple','e'=>'six'], [1=>'master','b'=>18,2=>5,'a'=>'admin'] ]; array_multisort($arr4); print_r($arr4); 输出结果: Array ( [0] => Array ( [a] => father [f] => before [d] => apple [e] => six ) [1] => Array ( [1] => master [b] => 18 [2] => 5 [a] => admin ) [2] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) )
文档使用详解:https://www.php.net/manual/zh/function.array-multisort.php
8.natcasesort(); 用“自然排序”算法对数组进行不区分大小写字母的排序 。
natcasesort ( array
&$array
) : bool1 <?php 2 3 $arr = ['c'=>'apple', 'f'=>'tree', 'a'=>'father', 's'=>'teacher', 'g'=>'student',]; 4 natcasesort($arr); 5 6 print_r($arr);
输出结果:
Array
(
[c] => apple
[a] => father
[g] => student
[s] => teacher
[f] => tree
)
二、
8.shuffle(); 打乱数组。
shuffle ( array
&$array
) : bool<?php $arr = [1,2,3,4,5,6,7,8,9,10]; shuffle($arr); print_r($arr); 输出结果: Array ( [0] => 7 [1] => 6 [2] => 10 [3] => 1 [4] => 3 [5] => 9 [6] => 8 [7] => 4 [8] => 5 [9] => 2 )
9.array_rand(); 从数组中取出一个或多个随机的单元,并返回随机条目的一个或多个键。
array_rand ( array
$array
[, int $num
= 1 ] ) : mixed<?php $arr =['a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5,'f'=>6,'g'=>7,'h'=>8,'i'=>9,'j'=>10]; $keys = array_rand($arr,3); $keys = array_rand($arr3,3); print_r($keys); foreach( $keys as $v){ echo $arr3[$v]; echo "\n"; } 输出结果: Array ( [0] => b [1] => c [2] => f ) 2 3 6