Home Backend Development PHP Tutorial php二维数组排序详解_PHP

php二维数组排序详解_PHP

Jun 01, 2016 am 11:58 AM

有时候为了达到一定目的,需要对二维数组进行排序,现分享一下其实现的方法。
复制代码 代码如下:
$arr=array (
'1' => array ( 'date' => '2011-08-18', 'num' => 5 ) ,
'2' => array ( 'date' => '2011-08-20', 'num' => 3 ) ,
'3' => array ( 'date' => '2011-08-17', 'num' => 10 )
 )  ; $result = sysSortArray($arr,'num');这样运行之后的效果为:
$arr=array (
'1' => array ( 'date' => '2011-08-18', 'num' => 3 ) ,
'2' => array ( 'date' => '2011-08-20', 'num' => 5 ) ,
'3' => array ( 'date' => '2011-08-17', 'num' => 10 )
 )  ;用到的函数:
/**
 * Sort an two-dimension array by some level two items use array_multisort() function.
 *
 * sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2";……)
 * @author                      lamp100
 * @param  array   $ArrayData   the array to sort.
 * @param  string  $KeyName1    the first item to sort by.
 * @param  string  $SortOrder1  the order to sort by("SORT_ASC"|"SORT_DESC")
 * @param  string  $SortType1   the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
 * @return array                sorted array.
 */
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
    if(!is_array($ArrayData))
    {
        return $ArrayData;
    }
    // Get args number.
    $ArgCount = func_num_args();
    // Get keys to sort by and put them to SortRule array.
    for($I = 1;$I     {
        $Arg = func_get_arg($I);
        if(!eregi("SORT",$Arg))
        {
            $KeyNameList[] = $Arg;
            $SortRule[]    = '$'.$Arg;
        }
        else
        {
            $SortRule[]    = $Arg;
        }
    }
    // Get the values according to the keys and put them to array.
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }
    // Create the eval string and eval it.
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}

另外:array_multisort 函数功能也很强大,详细可以参看PHP手册,里面讲的很详细。

我们可以使用array_multisort()这个函数。array_multisort() 函数对多个数组或多维数组进行排序。
参数中的数组被当成一个表的列并以行来进行排序 - 这类似 SQL 的 ORDER BY 子句的功能。第一个数组是要排序的主要数组。数组中的行(值)比较为相同的话,就会按照下一个输入数组中相应值的大小进行排序,依此类推。
第一个参数是数组,随后的每一个参数可能是数组,也可能是下面的排序顺序标志(排序标志用于更改默认的排列顺序)之一:
•SORT_ASC - 默认,按升序排列。(A-Z)
•SORT_DESC - 按降序排列。(Z-A)
随后可以指定排序的类型:
•SORT_REGULAR - 默认。将每一项按常规顺序排列。
•SORT_NUMERIC - 将每一项按数字顺序排列。
•SORT_STRING - 将每一项按字母顺序排列。
语法:array_multisort(array1,sorting order,sorting type,array2,array3...)
•array1:必需。规定输入的数组。
•sorting order:可选。规定排列顺序。可能的值是 SORT_ASC 和 SORT_DESC。
•sorting type:可选。规定排序类型。可能的值是SORT_REGULAR、SORT_NUMERIC和SORT_STRING。
•array2:可选。规定输入的数组。
•array3:可选。规定输入的数组。
字符串键名将被保留,但是数字键将被重新索引,从 0 开始,并以 1 递增。可以在每个数组后设置排序顺序和排序类型。如果没有设置,每个数组参数会使用默认值。
下面是一个例子:
复制代码 代码如下:

 $arr = '';

 echo '二维数组如下:'.'
';
 for($i=0; $i {
  $arr[$i]['val'] = mt_rand(1, 100);
  $arr[$i]['num'] = mt_rand(1, 100);
 }

 echo '

';<br> print_r($arr);<br> echo '
Copy after login
';

 echo '从二维数组中抽出键为val,单独成另一个数组:'.'
';
 foreach ($arr as $key => $row)
 {
     $vals[$key] = $row['val'];
        $nums[$key] = $row['num'];
 }

 echo '
';<br> print_r($vals);<br> echo '
Copy after login
Copy after login
';

 echo '对其进行排序:'.'
';
 array_multisort($vals, SORT_ASC, $arr);

 echo '
';<br> print_r($vals);<br> echo '
Copy after login
Copy after login
';

?>
 
运行结果:
二维数组如下:
Array
(
    [0] => Array
        (
            [val] => 46
            [num] => 49
        )
    [1] => Array
        (
            [val] => 8
            [num] => 24
        )
    [2] => Array
        (
            [val] => 37
            [num] => 3
        )
    [3] => Array
        (
            [val] => 32
            [num] => 35
        )
    [4] => Array
        (
            [val] => 19
            [num] => 38
        )
    [5] => Array
        (
            [val] => 30
            [num] => 37
        )
)
从二维数组中抽出键为val,单独成另一个数组:
Array
(
    [0] => 46
    [1] => 8
    [2] => 37
    [3] => 32
    [4] => 19
    [5] => 30
)
对其进行排序:
Array
(
    [0] => 8
    [1] => 19
    [2] => 30
    [3] => 32
    [4] => 37
    [5] => 46
)
我们将得到一个按val升序排序的二维数组。
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)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles