Home php教程 php手册 php数组排序的各种方法总结

php数组排序的各种方法总结

May 25, 2016 pm 04:56 PM
php array

在php中我们要对一维数组排序做起来很简单我们只要用到sort(),rsort()这样就完成了,如果要对多维数据排序的话php还没这类函数这个就需要我们自己来做了。

对于php数组排序在php中提供了很多的函数,下面我列出来,不全的大家可以补充。

sort() 函数用于对数组单元从低到高进行排序。
rsort() 函数用于对数组单元从高到低进行排序。
asort() 函数用于对数组单元从低到高进行排序并保持索引关系。
arsort() 函数用于对数组单元从高到低进行排序并保持索引关系。
ksort() 函数用于对数组单元按照键名从低到高进行排序。
krsort() 函数用于对数组单元按照键名从高到低进行排序。

不过今天我们主要是不是讲php自带的数组排序函数主要是讲自定的排序


一、冒泡排序法
  说明:找到最大的数,排列到最后面,然后继续找
 
例:

 代码如下 复制代码
$arr = array(3,5,-1,0,2);
for($i=0;$i    for($j=0;$j        if($arr[$j]>$arr[$j+1]){
            $temp = $arr[$j];
            $arr[$j]=$arr[$j+1];
            $arr[$j+1]=$temp;
        }
    }
}

理解:
3,5,-1,0,2
    //从第一个数开始往后比较,如果比后面的数大则与后面的数调位置
    //第一次,3小于5,那么不变
    //第二次,5大于-1,那么变成
3,-1,5,0,2
    //第三次,5大于0
3,-1,0,5,2
    //第四次,5大于2
3,-1,0,2,5
    至此完成一次内循环,此时最后一个数完成排序,下次将不参与
3,-1,0,2,5第二次外循环开始    第一次:3大于-1
-1,3,0,2,5
    第二次:3大于0
-1,0,3,2,5
    第三次:3大于2
-1,0,2,3,5
    至此完成后面两位数的排序了,接下来类推
-1,0,2,3,5
二、选择排序法    说明:先假设第一个数就是最小的数,然后将后面的数依次与它比较,如果假设的数不是最小的数,就将它与后面的最小的数调换位置

 代码如下 复制代码
$arr=array(2,1,-1,3,0);
for($i=0;$i    $minval = $arr[$i];
    $minindex = $i;
    for($j=1+$i;$j        if($arr[$j]            $minval = $arr[$j];
            $minindex = $j;
        }
    }
    $temp = $arr[$i];
    $arr[$i] = $arr[$minindex];
    $arr[$minindex] = $temp;
}

理解:
2,1,-1,3,0
    //先假设第一个数2为最小值,它后面的数依次与2做比较,寻找到最小的那个数
过程:
1小于2,那么minval=1
-1小于1,那么minval=-1
3大于-1,不变
0大于-1,不变
那么现在就找到了该数组中最小的数了为-1
将-1与2调换位置就完成第一个数的排序了
那么现在数组变成
-1,1,2,3,0
现在第一个数-1已经为有序,所以不参与比较了,往后面继续
现在假设minval=1
2大于1,不变
3大于1,不变
0小于1,那么minval=0
现在一次循环完成,调换0与1的位置完成第二个数的排序
那么现在数组变成
-1,0,2,3,1
//后面的推法与上面相同。。。
 
三、插入排序法说明:先假设一个数组中的第一个数为单独的有序数组,再将后面的一个数与它【这里随它I的增长,就变成它们了】做比较,如果后面的数比假设的数还小,则将小的那个数后移,最后将那个数移到最前面

 代码如下 复制代码
$arr=array(2,1,-1,3,0);
for($i=1;$i    $insertval=$arr[$i];
    $insertindex = $i-1;
    while($insertindex>=0 && $insertval        $arr[$insertindex+1]=$arr[$insertindex];
        $insertindex--;
    }
    $temp = $arr[$i];
    $arr[$insertindex+1]=$insertval;
}

理解:
2,1,-1,3,0
    //第一次,先保存待插入的数1为insertval,再拿 insertval 与2比较,1小于2,所以把2后移,变成如下的图
2,2,-1,3,0
    //此时2前面没有数字了,insertindex=0,所以比较完成,那么将insertval插入到寻找到的这个位置。变成如下图
1,2,-1,3,0
    //此时,1,2变成有序数组
    //第二次,先保存待插入的数-1为insertval,再拿insertval与2做比较,-1小于2,所以把2后移,变成如下图
1,2,2,3,0
    //此时,再拿insertval与1做比较,-1小于1,那么把-1后移,变成如下图(这就是一个拿待插入数与前面的有序数组比较的过程)
1,1,2,3,0
    //此时,insertindex到头了,所以将insertval插入该位置
-1,1,2,3,0
    //后面推法如上


二维数组排序函数,可以实现类似 MySQL 的 ORDER BY 效果,当数组不是从数据库取得时会有特殊应用。

 

 代码如下 复制代码

// 说明:PHP中二维数组的排序方法

 
/**
 * @package     BugFree
 * @version     $Id: FunctionsMain.inc.php,v 1.32 2005/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"……)
 * @author                      Chunsheng Wang
 * @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;
}
 
//################# 示例 #################
$arr = array(
    array(
        'name'      =>   '学习',
        'size'      =>   '1235',
        'type'      =>   'jpe',
        'time'      =>   '1921-11-13',
        'class'     =>   'dd',
    ),
    array(
        'name'      =>   '中国功夫',
        'size'      =>   '153',
        'type'      =>   'jpe',
        'time'      =>   '2005-11-13',
        'class'     =>   'jj',
    ),
    array(
        'name'      =>   '编程',
        'size'      =>   '35',
        'type'      =>   'gif',
        'time'      =>   '1997-11-13',
        'class'     =>   'dd',
    ),
    array(
        'name'      =>   '中国功夫',
        'size'      =>   '65',
        'type'      =>   'jpe',
        'time'      =>   '1925-02-13',
        'class'     =>   'yy',
    ),
    array(
        'name'      =>   '中国功夫',
        'size'      =>   '5',
        'type'      =>   'icon',
        'time'      =>   '1967-12-13',
        'class'     =>   'rr',
    ),
);
 
print_r($arr);
 
//注意:按照数字方式排序时 153 比 65 小
$temp = sysSortArray($arr,"name","SORT_ASC","type","SORT_DESC","size","SORT_ASC","SORT_STRING");
 
print_r($temp);
 
?>

至于一维数组排序我们用php自带的函数就可以完全实现数据排序了,所以我们讲到的都是相对用自定函数无法完成我们需求的做法了。



本文地址:

转载随意,但请附上文章地址:-)

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 尊渡假赌尊渡假赌尊渡假赌

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)

How to use PHP arrays to generate and display charts and statistical graphs How to use PHP arrays to generate and display charts and statistical graphs Jul 15, 2023 pm 12:24 PM

How to use PHP arrays to generate and display charts and statistical graphs. PHP is a widely used server-side scripting language with powerful data processing and graphic generation capabilities. In web development, we often need to display charts and statistical graphs of data. Through PHP arrays, we can easily implement these functions. This article will introduce how to use PHP arrays to generate and display charts and statistical graphs, and provide relevant code examples. Introducing the necessary library files and style sheets Before starting, we need to introduce some necessary library files into the PHP file

How to use PHP arrays to generate dynamic slideshows and image displays How to use PHP arrays to generate dynamic slideshows and image displays Jul 15, 2023 pm 01:17 PM

How to use PHP arrays to generate dynamic slideshows and picture displays. Slideshows and picture displays are common functions in web design and are often used in scenarios such as carousels and gallery displays. As a popular server-side scripting language, PHP has the ability to process data and generate dynamic HTML pages, and is very suitable for generating dynamic slideshows and picture displays. This article will introduce how to use PHP arrays to generate dynamic slideshows and picture displays, and give corresponding code examples. Prepare image data First, we need to prepare a set of image path data

How to use PHP arrays to implement user login and permission management functions How to use PHP arrays to implement user login and permission management functions Jul 15, 2023 pm 08:55 PM

How to use PHP arrays to implement user login and permission management functions When developing a website, user login and permission management are one of the very important functions. User login allows us to authenticate users and protect the security of the website. Permission management can control users' operating permissions on the website to ensure that users can only access the functions for which they are authorized. In this article, we will introduce how to use PHP arrays to implement user login and permission management functions. We'll use a simple example to demonstrate this process. First we need to create

What are the functions for averaging arrays in php? What are the functions for averaging arrays in php? Jul 17, 2023 pm 04:03 PM

PHP array averaging functions include: 1. array_sum(), which is used to calculate the sum of all values ​​in the array. In order to calculate the average, you can add all the values ​​in the array and then divide by the number of array elements; 2 , array_reduce(), used to iterate the array and calculate each value with an initial value; 3. array_mean(), used to return the average of the array, first calculate the sum of the array, and calculate the number of array elements, then The sum is divided by the number of array elements to get the average.

How to determine how many arrays there are in php How to determine how many arrays there are in php Aug 04, 2023 pm 05:40 PM

There are several ways to determine an array in PHP: 1. Use the count() function, which is suitable for all types of arrays. However, it should be noted that if the parameter passed in is not an array, the count() function will return 0; 2. Use the sizeof() function, which is more used to maintain compatibility with other programming languages; 3. Custom functions, By using a loop to traverse the array, each time it is traversed, the counter is incremented by 1, and finally the length of the array is obtained. Custom functions can be modified and expanded according to actual needs, making them more flexible.

An exploration of performance optimization techniques for PHP arrays An exploration of performance optimization techniques for PHP arrays Mar 13, 2024 pm 03:03 PM

PHP array is a very common data structure that is often used during the development process. However, as the amount of data increases, array performance can become an issue. This article will explore some performance optimization techniques for PHP arrays and provide specific code examples. 1. Use appropriate data structures In PHP, in addition to ordinary arrays, there are some other data structures, such as SplFixedArray, SplDoublyLinkedList, etc., which may perform better than ordinary arrays in certain situations.

What are php array key-value pairs? What are php array key-value pairs? Aug 03, 2023 pm 02:20 PM

PHP array key-value pair is a data structure consisting of a key and a corresponding value. The key is the identifier of the array element, and the value is the data associated with the key. It allows us to store and access data using keys as identifiers. By using key-value pairs, we can more easily operate and manage elements in the array, making program development more flexible and efficient.

What is the function in PHP to determine if an array is empty? What is the function in PHP to determine if an array is empty? Aug 03, 2023 pm 05:15 PM

The functions that PHP uses to determine if an array is empty are the "empty()" function and the "count()" function. 1. The "empty()" function is used to determine whether a variable is empty, including determining whether an array is empty. Its syntax is "empty($variable)"; 2. The "count()" function is used to count arrays. The number of elements, the syntax is "count($array)".

See all articles