Let's look at the two-dimensional array sort instances by a field.
| The code is as follows: |
Copy code |
<? Php
/**
* @ Author yebihai http://www.111cn.net
* @ Desc sort by a field in a two-dimensional array.
* @ Data
* $ TestData = array (
Array ('price' => 19 ),
Array ('price' => 121 ),
Array ('price' => 115 ),
Array ('price' => 113 ),
Array ('price' => 112)
);
*/
Class sortClass {
// Ascending
Function sortArrayAsc ($ preData, $ sortType = 'price '){
$ SortData = array ();
Foreach ($ preData as $ key_ I => $ value_ I ){
$ Price_ I = $ value_ I [$ sortType];
$ Min_key = '';
$ Sort_total = count ($ sortData );
Foreach ($ sortData as $ key_j => $ value_j ){
If ($ price_ I <$ value_j [$ sortType]) {
$ Min_key = $ key_j + 1;
Break;
}
}
If (empty ($ min_key )){
Array_push ($ sortData, $ value_ I );
} Else {
$ SortData1 = array_slice ($ sortData, 0, $ min_key-1 );
Array_push ($ sortData1, $ value_ I );
If ($ min_key-1) <$ sort_total ){
$ SortData2 = array_slice ($ sortData, $ min_key-1 );
Foreach ($ sortData2 as $ value ){
Array_push ($ sortData1, $ value );
}
}
$ SortData = $ sortData1;
}
}
Return $ sortData;
}
// Descending order
Function sortArrayDesc ($ preData, $ sortType = 'price '){
$ SortData = array ();
Foreach ($ preData as $ key_ I => $ value_ I ){
$ Price_ I = $ value_ I [$ sortType];
$ Min_key = '';
$ Sort_total = count ($ sortData );
Foreach ($ sortData as $ key_j => $ value_j ){
If ($ price_ I> $ value_j [$ sortType]) {
$ Min_key = $ key_j + 1;
Break;
}
}
If (empty ($ min_key )){
Array_push ($ sortData, $ value_ I );
} Else {
$ SortData1 = array_slice ($ sortData, 0, $ min_key-1 );
Array_push ($ sortData1, $ value_ I );
If ($ min_key-1) <$ sort_total ){
$ SortData2 = array_slice ($ sortData, $ min_key-1 );
Foreach ($ sortData2 as $ value ){
Array_push ($ sortData1, $ value );
}
}
$ SortData = $ sortData1;
}
}
Return $ sortData;
}
} |
Sort the functions of array sorting.
Data sorting functions include:
• The sort () function is used to sort array units from low to high.
• Rsort () is used to sort array units from high to low.
• The asort () function is used to sort array units from low to high and maintain the index relationship.
• Arsort () is used to sort array units from high to low and maintain the index relationship.
• The ksort () function is used to sort array cells by key names from low to high.
• The krsort () function is used to sort array cells by key names from high to low.
The array_multisort () function sorts multiple arrays or multi-dimensional arrays.