Home Backend Development PHP Tutorial php中二维数组排序问题方法详解_PHP

php中二维数组排序问题方法详解_PHP

May 30, 2016 am 08:44 AM

PHP中二维数组排序,可以使用PHP内置函数uasort()

示例一:

使用用户自定义的比较函数对数组中的值进行排序并保持索引关联

回调函数如下:注意回调函数的返回值是负数或者是false的时候,表示回调函数的第一个参数在前,第二个参数在后排列

$person = array(
  array('num'=>'001','id'=>6,'name'=>'zhangsan','age'=>21),
  array('num'=>'001','id'=>7,'name'=>'ahangsan','age'=>23),
  array('num'=>'003','id'=>1,'name'=>'bhangsan','age'=>23),
  array('num'=>'001','id'=>3,'name'=>'dhangsan','age'=>23),
);
//负数或者false表示第一个参数应该在前
function sort_by_name($x,$y){
  return strcasecmp($x['name'],$y['name']);
}
Copy after login

使用如下:

uasort($person,'sort_by_name');
Copy after login

下面给出一个二维数组排序的方法,供参考和面试使用:

//$array 要排序的数组
//$row  排序依据列
//$type 排序类型[asc or desc]
//return 排好序的数组
function array_sort($array,$row,$type){
  $array_temp = array();
  foreach($array as $v){
    $array_temp[$v[$row]] = $v;
  }
  if($type == 'asc'){
    ksort($array_temp);
  }elseif($type='desc'){
    krsort($array_temp);
  }else{
  }
  return $array_temp;
}
Copy after login

示例二:

一维数组排序可以使用asort、ksort等一些方法进程排序,相对来说比较简单。二维数组的排序怎么实现呢?使用array_multisort和usort可以实现

例如像下面的数组:

代码如下:

$users = array(
  array('name' => 'tom', 'age' => 20)
  , array('name' => 'anny', 'age' => 18)
  , array('name' => 'jack', 'age' => 22)
);
Copy after login

希望能按照age从小到大进行排序。笔者整理了两个方法出来,分享给大家。

1、使用array_multisort

使用这个方法,会比较麻烦些,要将age提取出来存储到一维数组里,然后按照age升序排列。具体代码如下:

代码如下:

$ages = array();
foreach ($users as $user) {
  $ages[] = $user['age'];
}
array_multisort($ages, SORT_ASC, $users);
Copy after login

执行后,$users就是排序好的数组了,可以打印出来看看。如果需要先按年龄升序排列,再按照名称升序排列,方法同上,就是多提取一个名称数组出来,最后的排序方法这样调用:

代码如下:

array_multisort($ages, SORT_ASC, $names, SORT_ASC, $users);
Copy after login

2、使用usort

使用这个方法最大的好处就是可以自定义一些比较复杂的排序方法。例如按照名称的长度降序排列:

代码如下:

usort($users, function($a, $b) {
      $al = strlen($a['name']);
      $bl = strlen($b['name']);
      if ($al == $bl)
        return 0;
      return ($al > $bl) ? -1 : 1;
    });
Copy after login

这里使用了匿名函数,如果有需要也可以单独提取出来。其中$a, $b可以理解为$users数组下的元素,可以直接索引name值,并计算长度,而后比较长度就可以了。

=====================================================================

这里顺便说一下PHP排序的几个函数

sort 对数组排序一般适用于一维索引数组,不会保持索引

rsort 对数组逆向排序 和sort用法一致

asort 对数组进行排序并保持索引关系对值进行排序,一般适用于一维数组,保持索引关系

arsort 对数组进行逆向排序并保持索引关系和asort用法一致

ksort 对数组按照键名排序

krsort 对数组按照键名逆向排序

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 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)

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' =>

How to Register and Use Laravel Service Providers How to Register and Use Laravel Service Providers Mar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

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

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

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.

See all articles