Home >Backend Development >PHP Tutorial >How to sort a two-dimensional array by a certain field in PHP? _PHP Tutorial
There are many ready-made functions for data sorting, but if you want to sort specified fields, there are no built-in functions. Below I have compiled some related array sorting functions to share and learn with you.
Let’s not talk about anything else. Let’s look directly at an example of sorting a two-dimensional array by a certain field
代码如下 | 复制代码 |
/** * @author yebihai http://www.bKjia.c0m * @desc Sort ascending and descending according to a certain field of the two-dimensional array * @data * * $testData = array( array('price'=>19), array('price'=>121), array('price'=>115), array('price'=>113), array('price'=>112) ); */ class sortClass{ //升序 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; } //降序 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; } We will sort out some functions about array sorting later The data sorting function has | •The sort() function is used to sort array cells from low to high.
•The arsort() function is used to sort the array cells from high to low and maintain the index relationship.
•The ksort() function is used to sort array cells from low to high by key name.•The krsort() function is used to sort array cells from high to low by key name.
The array_multisort() function sorts multiple arrays or multidimensional arrays