I have introduced many methods for sorting two-dimensional arrays. Here I can see a php two-dimensional array multi-element sorting example written by a netizen. Let's take a look. I have introduced many methods for sorting two-dimensional arrays. Here I can see a php two-dimensional array multi-element sorting example written by a netizen. Let's take a look.
Script ec (2); script
Write a two-dimensional array of Multi-Element sorting. Multi-Element sorting is similar to order by sort and date in SQL. The following Code considers performance issues and only involves two elements for sorting.
Code area:
Function multipleArraySort ($ old_arr, $ arr1, $ arr2 ){
// Sort the first element
$ Old_arr = array_sort ($ old_arr, $ arr1 [0], $ arr1 [1]);
$ Temp_array = $ new_temp_array = array ();
Foreach ($ old_arr as $ k => $ v ){
$ Key_count = count ($ old_arr)-1;
// Put the first element into a temporary array with equal numbers
If ($ v [$ arr1 [0] = $ old_arr [$ k-1] [$ arr1 [0] | empty ($ temp_array )){
$ Temp_array [$ k] = $ v;
}
If ($ v [$ arr1 [0]! = $ Old_arr [$ k-1] [$ arr1 [0] &! Empty ($ temp_array) | $ key_count = $ k ){
// Add the latest element
$ Temp_array [$ k] = $ v;
// Sort an array larger than 1
If (count ($ temp_array)> 1 ){
If ($ key_count! = $ K ){
// Delete the last element (not equal to the previous element)
Unset ($ temp_array [$ k]);
}
// Sorting is not the last or last same
If ($ key_count! = $ K | $ v [$ arr1 [0] = $ old_arr [$ k-1] [$ arr1 [0]) {
// Sort the second element
$ Temp_array = array_sort ($ temp_array, $ arr2 [0], $ arr2 [1]);
}
// Insert the sorted array to the position before sorting the original array.
$ Count = count ($ new_temp_array) = 0? 0: count ($ new_temp_array );
Foreach ($ temp_array as $ val_t ){
$ New_temp_array [$ count] = $ val_t;
$ Count ++;
}
// Empty the original array after writing the new array
$ Temp_array = array ();
// Add the latest element
$ Temp_array [$ k] = $ v;
}
}
}
Return $ new_temp_array;
}
// Sort by array elements
Function array_sort ($ arr, $ keys, $ type = 'asc '){
$ Keysvalue = $ new_array = array ();
// Obtain the element value to generate a new array
Foreach ($ arr as $ k =>$ v ){
$ Keysvalue [$ k] = $ v [$ keys];
}
// Sort. The default value is positive.
If ($ type = 'asc '){
Asort ($ keysvalue );
} Else {
Arsort ($ keysvalue );
}
Reset ($ keysvalue );
$ Count_s = 0;
// Restore the key value
Foreach ($ keysvalue as $ k => $ v ){
$ New_array [$ count_s] = $ arr [$ k];
$ Count_s ++;
}
Return $ new_array;
}
Call method:
$ Old_arr = array (
Array ('id' => 1, 'sort '=> 1, 'date' => '123 '),
Array ('id' => 2, 'sort '=> 1, 'date' => '123 '),
Array ('id' => 3, 'sort '=> 2, 'date' => '123 '),
);
$ Arr1 = array ('sort ', 'desc ');
$ Arr2 = array ('date', 'desc ');
$ NewArr = multipleArraySort ($ old_arr, $ arr1, $ arr2 );
Var_dump ($ newArr );
Print result: