I will not talk about the definition of php two-dimensional arrays. It is very simple. The following examples are about sorting and traversing php two-dimensional arrays, every instance introduces php two-dimensional array sorting in different ways.
I will not talk about the two-dimensional array definition in the php tutorial. It is very simple. The following examples are all aboutPhp 2D array sortingWith traversal, every instance is introduced in a different way.Php 2D array sorting.
Function multi_array_sort ($ multi_array, $ sort_key, $ sort = sort_asc ){
If (is_array ($ multi_array )){
Foreach ($ multi_array as $ row_array ){
If (is_array ($ row_array )){
$ Key_array [] = $ row_array [$ sort_key];
} Else {
Return-1;
}
}
} Else {
Return-1;
}
Array_multisort ($ key_array, $ sort, $ multi_array );
Return $ multi_array;
}
Array (
Array ('id' => 1, 'data' => 'A '),
Array ('id' => 3, 'data' => 'C '),
Array ('id' => 2, 'data' => 'B ')
);
Php itself has a function for sorting multi-dimensional arrays.
Bool array_multisort (array $ ar1 [, mixed $ arg [, mixed $... [, array $...])
Method 2
// Sort two-dimensional arrays in descending order with the time inputdate as the key value
Function array_sort ($ arr, $ keys, $ type ){
$ Keysvalue = array ();
$ I = 0;
Foreach ($ arr as $ key => $ val ){
$ Val [$ keys] = str_replace ("-", "", $ val [$ keys]);
$ Val [$ keys] = str_replace ("", "", $ val [$ keys]);
$ Val [$ keys] = str_replace (":", "", $ val [$ keys]);
$ Keysvalue [] = $ val [$ keys];
}
Asort ($ keysvalue); // sort key values
Reset ($ keysvalue); // The Pointer Points to the first array.
Foreach ($ keysvalue as $ key => $ vals ){
$ Keysort [] = $ key;
}
$ New_array = array ();
If ($ type! = "Asc "){
For ($ ii = count ($ keysort)-1; $ ii> = 0; $ ii --){
$ New_array [] = $ arr [$ keysort [$ ii];
}
} Else {
For ($ ii = 0; $ ii $ New_array [] = $ arr [$ keysort [$ ii];
}
}
Return $ new_array;
}
?>
Method 3
$ A = array (
0 => array ("id" => 1, "name" => "", "addr" => "),
1 => array ("id" => 2, "name" => "Xiaogang", "addr" => "),
2 => array ("id" => 3, "name" => "Xiaojun", "addr" => "),
3 => array ("id" => 4, "name" => "company", "addr" => "0: 4 "),
);
Function sort_by ($ array, $ keyname = null, $ sortby ){
$ Myarray = $ inarray = array ();
Foreach ($ array as $ I =>$ befree ){
$ Myarray [$ I] = $ array [$ I] [$ keyname];
}
Switch ($ sortby ){
Case 'asc ':
Asort ($ myarray );
Break;
Case 'arsort ':
Arsort ($ myarray );
Break;
Case 'natcase ':
Natcasesor ($ myarray );
Break;
}
Foreach ($ myarray as $ key => $ befree ){
$ Inarray [$ key] = $ array [$ key];
}
Return $ inarray;
}
Print_r (sort_by ($ a, "addr", "arsort "));
Print_r ($ a [2] ["id"]);
?>