First look at the Array_multisort () function
| The code is as follows |
Copy Code |
|
<?php
$ar = Array (
Array ("A", "one, One,", "a"),
Array (1, 2, "2", 3, 1)
);
Array_multisort ($ar [0], SORT_ASC, sort_string,
$ar [1], sort_numeric, SORT_DESC);
Var_dump ($ar);
?> |
In this example, after sorting, the first array becomes "Ten", 100,100,11, and "a" (sorted in ascending order as a string). The second array will contain 1, 3, "2", 2, 1 (sorted as numbers in descending order).
| The code is as follows |
Copy Code |
|
Array (2) {
[0]=> Array (5) {
[0]=> string (2) "10"
[1]=> Int (100)
[2]=> Int (100)
[3]=> Int (11)
[4]=> string (1) "a"
}
[1]=> Array (5) {
[0]=> Int (1)
[1]=> Int (3)
[2]=> string (1) "2"
[3]=> Int (2)
[4]=> Int (1)
}
} |
The above is not very convenient to use ready-made functions, I would like to recommend a user-defined function
| The code is as follows |
Copy Code |
function Array_sort ($arr, $keys, $type = ' asc ') {
$keysvalue = $new _array = Array ();
foreach ($arr as $k => $v) {
$keysvalue [$k] = $v [$keys];
}
if ($type = = ' asc ') {
Asort ($keysvalue);
}else{
Arsort ($keysvalue);
}
Reset ($keysvalue);
foreach ($keysvalue as $k => $v) {
$new _array[$k] = $arr [$k];
}
return $new _array;
} |
Test (it can sort a two-dimensional array by the specified key value, or you can specify ascending or descending sort (default is ascending),
Usage examples:
| The code is as follows |
Copy Code |
|
$array = Array (
Array (' name ' => ' cell phone ', ' brand ' => ' Nokia ', ' Price ' =>1050),
Array (' name ' => ' laptop ', ' brand ' => ' Lenovo ', ' Price ' =>4300),
Array (' name ' => ' Razor ', ' Brand ' => ' Philips ', ' Price ' =>3100),
Array (' name ' => ' treadmill ', ' brand ' => ' three and pine stone ', ' price ' =>4900),
Array (' name ' => ' watch ', ' brand ' => ' Casio ', ' Price ' =>960),
Array (' name ' => ' LCD tv ', ' Brand ' => ' Sony ', ' Price ' =>6299),
Array (' name ' => ' laser printer ', ' Brand ' => ' hp ', ' Price ' =>1200)
);
$ShoppingList = Array_sort ($array, ' price ');
Print_r ($ShoppingList); |
Bubble method
| The code is as follows |
Copy Code |
|
function ArraySort ($data, $order = ' asc ') {
ASC Ascending desc Descending
$temp = Array ();
$count = count ($data);
if ($count <= 0)
return false; Incorrect data passed in
if ($order = = ' asc ') {
for ($i = 0; $i < $count; $i + +) {
for ($j = $count-1; $j > $i; $j-) {
if ($data [$j] < $data [$j-1]) {
Swap two data locations
$temp = $data [$j];
$data [$j] = $data [$j-1];
$data [$j-1] = $temp;
}
}
}
} else {
for ($i = 0; $i < $count; $i + +) {
for ($j = $count-1; $j > $i; $j-) {
if ($data [$j] > $data [$j-1]) {
$temp = $data [$j];
$data [$j] = $data [$j-1];
$data [$j-1] = $temp;
}
}
}
}
return $data;
}
$data = Array (7, 5, 3, 8, 9, 1, 5, 3, 1, 24, 3, 87, 0, 33, 1, 12, 34);
Var_dump (ArraySort ($data));//Ascending
Echo (' <br> ');
Var_dump (ArraySort ($data, ' desc '));//Descending
|