# Php two-dimensional array grouping and sorting implementation code

Source: Internet
Author: User

Group sorting

 The code is as follows: Copy code \$ val ){Asort (\$ new [\$ key]); // sort the data in each group;\$ Tmp = \$ new [\$ key]; // assign the sorted data to a temporary array;\$ Tmp [] = \$ key; // add the key value of the original array to the end of the temporary array to prepare for the subsequent modification of the key value;\$ A = array_shift (\$ new [\$ key]); // extract the first (minimum) data of each group. Take the aa group as an example, \$ a: The value is 33;\$ Aa [\$ a] = \$ tmp; // create an array with \$ aa (for example, 33) as the key value;Ksort (\$ aa); // Sort by key value     } Foreach (\$ aa as \$ key => \$ val) {// array sorted by key value, which has lost the original key value, for example, aa/bb/cc/dd. Fortunately, we have saved the key value to the end of the temporary array;\$ B = array_pop (\$ aa [\$ key]); // Obtain the key value;\$ Bb [\$ B] = \$ aa [\$ key]; // create an array and use the previous key value (aa/bb/cc)     } Return \$ bb; // return}\$ C = arr_group_sort (\$ new );Print_r (\$ new); // original array;Print_r (\$ c); // Array after grouping;?>

Other two-dimensional array sorting methods

 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;}

It can sort two-dimensional arrays by specified key values, or specify the ascending or descending sort method (the default is ascending). Usage example:

 The code is as follows: Copy code \$ Array = 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', 'price' => 4900 ),Array ('name' => 'Watch ', '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 );
Related Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD