Home php教程 php手册 php 二维数组排序几种方法

php 二维数组排序几种方法

May 25, 2016 pm 04:54 PM
foreach

二维数组排序排序在php中也提供了一个函数array_multisort就可以直接排序了,下面我来介绍除了全使用array_multisort 对数组进行排序我们还写了一些自定二维数组排序方法。

有时候为了达到一定目的,需要对二维数组进行排序,现分享一下其实现的方法。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

<?php

$arr = array(

    &#39;1&#39; => array(

        &#39;date&#39; => &#39;2011-08-18&#39;,

        &#39;num&#39; => 5

    ) ,

    &#39;2&#39; => array(

        &#39;date&#39; => &#39;2011-08-20&#39;,

        &#39;num&#39; => 3

    ) ,

    &#39;3&#39; => array(

        &#39;date&#39; => &#39;2011-08-17&#39;,

        &#39;num&#39; => 10

    )

);

$result = sysSortArray($arr, &#39;num&#39;); //这样运行之后的效果为:

$arr = array(

    &#39;1&#39; => array(

        &#39;date&#39; => &#39;2011-08-18&#39;,

        &#39;num&#39; => 3

    ) ,

    &#39;2&#39; => array(

        &#39;date&#39; => &#39;2011-08-20&#39;,

        &#39;num&#39; => 5

    ) ,

    &#39;3&#39; => array(

        &#39;date&#39; => &#39;2011-08-17&#39;,

        &#39;num&#39; => 10

    )

);

//用到的函数:

/**

 * @package     二维数组排序

 * @version     $Id: FunctionsMain.inc.php,v 1.32 2011/09/24 11:38:37 wwccss Exp $

 *

 *

 * Sort an two-dimension array by some level two items use array_multisort() function.

 *

 * sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2";&hellip;&hellip;)

 * @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 < $ArgCount; $I++) {

        $Arg = func_get_arg($I);

        if (!eregi("SORT", $Arg)) {

            $KeyNameList[] = $Arg;

            $SortRule[] = &#39;$&#39; . $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 = &#39;array_multisort(&#39; . join(",", $SortRule) . &#39;,$ArrayData);&#39;;

    eval($EvalString);

    return $ArrayData;

}

?>

Copy after login

另外: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 递增。可以在每个数组后设置排序顺序和排序类型。如果没有设置,每个数组参数会使用默认值。

下面是一个例子:

1

2

3

4

5

6

7

8

9

10

<?php

$arr = &#39;&#39;;

echo &#39;二维数组如下:&#39; . &#39;<br / >&#39;;

for ($i = 0; $i <= 5; $i++) {

    $arr[$i][&#39;val&#39;] = mt_rand(1, 100);

    $arr[$i][&#39;num&#39;] = mt_rand(1, 100);

}

echo &#39;<pre class="brush:php;toolbar:false">&#39;;

print_r($arr);

echo &#39;

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

1

2

3

&#39;;

print_r($vals);

echo &#39;

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

1

2

3

&#39;;

print_r($vals);

echo &#39;

Copy after login
Copy after login
'; ?>

运行结果:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

二维数组如下:

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

)

Copy after login

我们将得到一个按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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? Apr 27, 2023 pm 03:40 PM

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

How to determine the number of foreach loop in php How to determine the number of foreach loop in php Jul 10, 2023 pm 02:18 PM

​The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

PHP returns an array with key values ​​flipped PHP returns an array with key values ​​flipped Mar 21, 2024 pm 02:10 PM

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values ​​in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values ​​swapped. $original_array=[

PHP returns the current element in an array PHP returns the current element in an array Mar 21, 2024 pm 12:36 PM

This article will explain in detail about the current element in the array returned by PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. Get the current element in a PHP array PHP provides a variety of methods for accessing and manipulating arrays, including getting the current element in an array. The following introduces several commonly used techniques: 1. current() function The current() function returns the element currently pointed to by the internal pointer of the array. The pointer initially points to the first element of the array. Use the following syntax: $currentElement=current($array);2.key() function key() function returns the array internal pointer currently pointing to the element

What is the difference between foreach and for loop What is the difference between foreach and for loop Jan 05, 2023 pm 04:26 PM

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

How to iterate through the properties of an object using the forEach function? How to iterate through the properties of an object using the forEach function? Nov 18, 2023 pm 06:10 PM

How to iterate through the properties of an object using the forEach function? In JavaScript, we often need to traverse the properties of objects. If you want to use a concise way to iterate over the properties of an object, the forEach function is a very good choice. In this article, we will explain how to use the forEach function to iterate over the properties of an object and provide specific code examples. First, let's understand the basic usage of the forEach function. forEach function is Java

Detailed explanation of the function and usage of break keyword in PHP Detailed explanation of the function and usage of break keyword in PHP Jun 28, 2023 pm 06:39 PM

Detailed explanation of the role and usage of the break keyword in PHP In PHP programming, break is a control flow statement used to interrupt the current loop or switch statement and jump out of the loop or switch. This article will introduce in detail the role and usage of the break keyword. 1. Break in a loop In a loop structure, the function of break is to terminate the loop early and jump out of the loop body to execute the code after the loop. Common loop structures include for, while and do...while. in for loop

Advanced skills of Java Map: Master cold knowledge you may not know and improve your programming skills Advanced skills of Java Map: Master cold knowledge you may not know and improve your programming skills Feb 19, 2024 pm 12:33 PM

Map interface overview The Map interface is a data structure used to store key-value pairs in the Java collection framework. It allows you to use keys to find and retrieve associated values. The Map interface provides many useful methods, including put(), get(), remove(), containsKey(), containsValue(), size(), isEmpty(), etc. Implementation of Map The most commonly used Map implementations in Java are HashMap and TreeMap. HashMap is a hash table-based Map implementation that quickly finds and retrieves values ​​by calculating the hash value of the key. TreeMap is a Map implementation based on red-black trees, which sorts keys in ascending or descending order.

See all articles