在php中array_multisort()可实现一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序,如果成功则返回 TRUE,失败则返回 FALSE.
bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]] )
如果成功则返回 TRUE,失败则返回 FALSE.
array_multisort() 可以用来一次对多个数组进行排序,或者根据某一维或多维对多维数组进行排序.
关联(string)键名保持不变,但数字键名会被重新索引.
例子 1. 对多维数组排序实例代码如下:
- <?php
- $ar = array(
- array("10", 11, 100, 100, "a"),
- array( 1, 2, "2", 3, 1)
- );
- array_multisort($ar[0], SORT_ASC, SORT_STRING,
- $ar[1], SORT_NUMERIC, SORT_DESC);
- var_dump($ar);
- ?>
In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).
实例代码如下:
- array(2) {
- [0]=> array(5) {
- [0]=> string(2) "10"
- [1]=> int(100)
- [2]=> int(100)
- [3]=> int(11)
- [4]=> string(1) "a"
- }
- [1]=> array(5) {
- [0]=> int(1)
- [1]=> int(3)
- [2]=> string(1) "2"
- [3]=> int(2)
- [4]=> int(1)
- }
- }
本例中经过排序后,第一个数组将包含 10,100,100,"a"(作为字符串上升排序),第二个数组将包含 1,3,"2",1(作为数值下降排序).
例子 2. Sorting multi-dimensional array实例代码如下:
- <?php
- $ar = array(
- array("10", 11, 100, 100, "a"),
- array( 1, 2, "2", 3, 1)
- );
- array_multisort($ar[0], SORT_ASC, SORT_STRING,
- $ar[1], SORT_NUMERIC, SORT_DESC);
- var_dump($ar);
- ?>
本例中在排序后,第一个数组将变成 "10",100,100,11,"a"(被当作字符串以升序排列).第二个数组将包含 1, 3, "2", 2, 1(被当作数字以降序排列).
实例代码如下:
- array(2) {
- [0]=> array(5) {
- [0]=> string(2) "10"
- [1]=> int(100)
- [2]=> int(100)
- [3]=> int(11)
- [4]=> string(1) "a"
- }
- [1]=> array(5) {
- [0]=> int(1)
- [1]=> int(3)
- [2]=> string(1) "2"
- [3]=> int(2)
- [4]=> int(1)
- }
- }
实例3 综合实现来看一个关于在应用中常用的实例代码如下:
- header('Content-Type: text/html; charset=utf-8');
- echo '<pre>';
-
- $array = array(
- 'key1' => array(
- 'item1' => '65',
- 'item2' => '35',
- 'item3' => '84',
- ),
- 'key2' => array(
- 'item1' => '24',
- ),
- 'key3' => array(
- 'item1' => '38',
- 'item3' => '45',
- ),
- );
-
-
-
- $sort = 'item1';
- foreach($array as $k => $v)
- {
- $newArr[$k] = $v[$sort];
- }
-
-
- array_multisort($newArr,SORT_DESC, $array);
- var_dump($array);
-
- array(3) {
- ["key1"]=>
- array(3) {
- ["item1"]=>
- string(2) "65"
- ["item2"]=>
- string(2) "35"
- ["item3"]=>
- string(2) "84"
- }
- ["key3"]=>
- array(2) {
- ["item1"]=>
- string(2) "38"
- ["item3"]=>
- string(2) "45"
- }
- ["key2"]=>
- array(1) {
- ["item1"]=>
- string(2) "24"
- }
- }
-
(责任编辑:admin) |