Home Backend Development PHP Tutorial PHP array_multisort() 函数的深入解析_PHP

PHP array_multisort() 函数的深入解析_PHP

Jun 01, 2016 pm 12:06 PM
array_multisort php

一、先看最简单的情况。有两个数组:
$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
array_multisort($arr1,$arr2);
print_r($arr1); // 得到的顺序是1,5,9
print_r($arr2); // 得到的顺序是6,4,2
我估计两个数组的值自始至终都是对应着的:1对应6,9对应2,5对应4。
我们再加多一个数组看看会怎样:
$arr1 = array(1,9,5);
$arr2 = array(6,2,4);
$arr3 = array(3,7,8);
array_multisort($arr1,$arr2,$arr3);
查看结果,1自始至终都对应6对应3,其它项也是如此。这种对应关系就是手册中所谓的“排序时保留原有的键名关联”。
另外也可以把每个数组想像成数据库表的一列。而对应着的1,6,3为一数据行,9,2,7为另一数据行。。。
array_multisort会先按第一个数组(想像成列)排序,如果第一个数组(列)的值相同,则按第二个数组(列)排序。
具体可以用下面的程式来测试:
$arr1 = array(1,9,5,9);
$arr2 = array(6,2,4,1);
$arr3 = array(3,7,8,0);
array_multisort($arr1,$arr2,$arr3);
可以想像这里$arr3的结果是(3,8,0,7)。

二、接下来讲解array_multisort的参数。这个函数的参数很灵活。最简单的情况是如上面所示的以1个或n个数组作为参数,需要注意的是每个数组的项数要一样,否则会warning导致排序失效。
像这样array_multisort($arr1,$arr2,$arr3); 默认是所有数组都是升序排列,如果想对$arr2降序,并当作字符串去比较,就要写成:
array_multisort($arr1, $arr2, SORT_DESC, SORT_STRING, $arr3);
每个array后面可以跟一个排序顺序标志或一个排序类型标志,或者两种标志同时出现。但是每种排序标志在每个数组后面只能出现一个。
详细如下:
排序顺序标志:
SORT_ASC - 按照上升顺序排序(默认)
SORT_DESC - 按照下降顺序排序
排序类型标志:
SORT_REGULAR - 将项目按照通常方法比较(默认)
SORT_NUMERIC - 将项目按照数值比较
SORT_STRING - 将项目按照字符串比较

三、最后是array_multisort有什么实际作用。
我们通常有一些多维数组需要排序:
复制代码 代码如下:
$guys = Array
(
    [0] => Array
        (
 [name] => jake
 [score] => 80
 [grade] => A
        )
    [1] => Array
        (
 [name] => jin
 [score] => 70
 [grade] => A
        )
    [2] => Array
        (
 [name] => john
 [score] => 80
 [grade] => A
        )
    [3] => Array
        (
 [name] => ben
 [score] => 20
 [grade] => B
        )
)

例如我们想按成绩倒序排列,如果成绩相同就按名字的升序排列。
这时我们就需要根据$guys的顺序多弄两个数组出来:
$scores = array(80,70,80,20);
$names = array('jake','jin','john','ben');
然后
array_multisort($scores, SORT_DESC, $names, $guys);就行了
还能不能更灵活一点呢,每次想排序都要另外弄些数组出来吗?
其实在qeephp的helper_array类里面已经封装得很好,下面是它的两个方法,需要的人自己修改一下就可以用了:
复制代码 代码如下:
/**
* 根据指定的键对数组排序
*
* 用法:
* @code php
* $rows = array(
*array('id' => 1, 'value' => '1-1', 'parent' => 1),
*array('id' => 2, 'value' => '2-1', 'parent' => 1),
*array('id' => 3, 'value' => '3-1', 'parent' => 1),
*array('id' => 4, 'value' => '4-1', 'parent' => 2),
*array('id' => 5, 'value' => '5-1', 'parent' => 2),
*array('id' => 6, 'value' => '6-1', 'parent' => 3),
* );
*
* $rows = Helper_Array::sortByCol($rows, 'id', SORT_DESC);
* dump($rows);
* // 输出结果为:
* // array(
* //         array('id' => 6, 'value' => '6-1', 'parent' => 3),
* //         array('id' => 5, 'value' => '5-1', 'parent' => 2),
* //         array('id' => 4, 'value' => '4-1', 'parent' => 2),
* //         array('id' => 3, 'value' => '3-1', 'parent' => 1),
* //         array('id' => 2, 'value' => '2-1', 'parent' => 1),
* //         array('id' => 1, 'value' => '1-1', 'parent' => 1),
* // )
* @endcode
*
* @param array $array 要排序的数组
* @param string $keyname 排序的键
* @param int $dir 排序方向
*
* @return array 排序后的数组
*/
          static function sortByCol($array, $keyname, $dir = SORT_ASC)
          {
   return self::sortByMultiCols($array, array($keyname => $dir));
          }
          /**
* 将一个二维数组按照多个列进行排序,类似 SQL 语句中的 ORDER BY
*
* 用法:
* @code php
* $rows = Helper_Array::sortByMultiCols($rows, array(
*'parent' => SORT_ASC,
*'name' => SORT_DESC,
* ));
* @endcode
*
* @param array $rowset 要排序的数组
* @param array $args 排序的键
*
* @return array 排序后的数组
*/
          static function sortByMultiCols($rowset, $args)
          {
   $sortArray = array();
   $sortRule = '';
   foreach ($args as $sortField => $sortDir)
   {
       foreach ($rowset as $offset => $row)
       {
$sortArray[$sortField][$offset] = $row[$sortField];
       }
       $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
   }
   if (empty($sortArray) || empty($sortRule)) { return $rowset; }
   eval('array_multisort(' . $sortRule . '$rowset);');
   return $rowset;
          }

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

See all articles