By GokiSoft.Com| 21:10 10/06/2020|
Tài Liệu PHP

PHP Sorting Arrays - Sắp xếp các phần tử trong mảng

Các phần tử trong một mảng có thể được sắp xếp theo thứ tự chữ cái hoặc số, giảm dần hoặc tăng dần.


PHP - Các hàm sắp xếp mảng

  • sort() - sắp xếp mảng theo thứ tự tăng dần
  • rsort() - sắp xếp mảng theo thứ tự giảm dần
  • asort() - sắp xếp associative arrays theo thứ tự tăng dần, theo value
  • ksort() - sắp xếp associative arrays theo thứ tự tăng dần, theo key
  • arsort() - sắp xếp associative arrays theo thứ tự giảm dần, theo value
  • krsort() - sắp xếp associative arrays theo thứ tự giảm dần, theo key

Sắp xếp tăng dần - sort()

Ví dụ sau đây sắp xếp các phần tử của mảng $cars theo thứ tự bảng chữ cái tăng dần:

Ví dụ

<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

Ví dụ sau đây sắp xếp các phần tử của mảng $numbers theo thứ tự số tăng dần:

<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>


Sắp xếp giảm dần - rsort()

Ví dụ sau đây sắp xếp các phần tử của mảng $cars theo thứ tự bảng chữ cái giảm dần:

<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

Ví dụ sau đây sắp xếp các phần tử của mảng $numbers theo thứ tự số giảm dần:

<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>


Sắp xếp tăng dần theo Value - asort()

Ví dụ sau sắp xếp một associative array theo thứ tự tăng dần, theo value:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>


Sắp xếp tăng dần theo Key - ksort()

Ví dụ sau sắp xếp một associative array theo thứ tự tăng dần, theo key:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>


Sắp xếp giảm dần theo Value - arsort()

Ví dụ sau sắp xếp một associative array theo thứ tự giảm dần, theo value:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>


Sắp xếp giảm dần theo Key - krsort()

Ví dụ sau sắp xếp một associative array theo thứ tự giảm dần, theo key:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>