Sắp xếp thứ tự trong array

PHP hỗ trợ các loại sort

 

-       sort() - sắp xếp mảng theo thứ tự tăng dần

-       rsort () - sắp xếp các mảng theo thứ tự giảm dần

-       asort () - sắp xếp mảng kết hợp theo thứ tự tăng dần, theo giá trị

-       ksort () - sắp xếp các mảng kết hợp theo thứ tự tăng dần, theo khóa

-       arsort () - sắp xếp mảng kết hợp theo thứ tự giảm dần theo giá trị

-       krsort () - sắp xếp các mảng kết hợp theo thứ tự giảm dần theo khoá

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

Ví dụ1:

<!DOCTYPE html>
<html>
<body>

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

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
    
echo $cars[$x];
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

BMW
Toyota
Volvo

Ví dụ2 :

<!DOCTYPE html>
<html>
<body>

<?php
$numbers = 
array(4622211);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
    
echo $numbers[$x];
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

2
4
6
11
22

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

Ví dụ1:

<!DOCTYPE html>
<html>
<body>

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

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
    
echo $cars[$x];
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

Volvo
Toyota
BMW

Ví dụ2:

<!DOCTYPE html>
<html>
<body>

<?php
$numbers = 
array(4622211);
rsort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
    
echo $numbers[$x];
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

22
11
6
4
2

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

Ví dụ:

<!DOCTYPE html>
<html>
<body>

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

foreach($age as $x => $x_value) {
    
echo "Key=" . $x . ", Value=" . $x_value;
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

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

Ví dụ:

<!DOCTYPE html>
<html>
<body>

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

foreach($age as $x => $x_value) {
    
echo "Key=" . $x . ", Value=" . $x_value;
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35

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

Ví dụ:

<!DOCTYPE html>
<html>
<body>

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

foreach($age as $x => $x_value) {
    
echo "Key=" . $x . ", Value=" . $x_value;
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

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

Ví dụ:

<!DOCTYPE html>
<html>
<body>

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

foreach($age as $x => $x_value) {
    
echo "Key=" . $x . ", Value=" . $x_value;
    
echo "<br>";
}
?>

</body>
</html>

Kết quả

Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37