PHP two-dimensional array sorting function PHP one-dimensional array sorting can use sort (), asort (), arsort () and other functions, but PHP two-dimensional array sorting needs to be customized. The following function sorts a given two-dimensional array by the specified key value. first look at the function definition: functionarray_sort ($ arr, $ keys, $ typeasc) {$ keysvalue $ ne
PHP two-dimensional array sorting function PHP one-dimensional array sorting can use sort (), asort (), arsort () and other functions, but PHP two-dimensional array sorting needs to be customized. The following function sorts a given two-dimensional array by the specified key value. first look at the function definition: function array_sort ($ arr, $ keys, $ type = 'asc ') {$ keysvalue = $ ne
PHP two-dimensional array sorting Function
You can use functions such as sort (), asort (), and arsort () to sort PHP one-dimensional arrays. However, you need to customize the sorting of PHP two-dimensional arrays.
The following function sorts a given two-dimensional array by the specified key value. First, let's look at the function definition:
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; }
It can sort two-dimensional arrays by specified key values, or specify the ascending or descending sort method (the default is ascending). Usage example:
$ Array = array ('name' => 'phone', 'brand' => 'nokia ', 'price' => 1050 ), array ('name' => 'laptop ', 'brand' => 'lenovo', 'price' => 4300), array ('name' => 'shares ', 'brand' => 'phillips', 'price' => 3100), array ('name' => 'treadmill ', 'brand' => 'three and two ', 'price' => 4900), array ('name' => 'watches ', 'brand' => 'case', '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 );
The above orders the two-dimensional array $ array in descending order of 'price.
Original article address: PHP two-dimensional array sorting function, thanks to the original author for sharing.