Home > Backend Development > PHP Tutorial > Sort specified items in a two-dimensional array

Sort specified items in a two-dimensional array

WBOY
Release: 2016-07-25 09:02:26
Original
1127 people have browsed it

  1. /*
  2. $array_name: the incoming array;
  3. $row_id: the items in the array that you want to sort;
  4. $order_type: the sorting method, ASC or DESC;
  5. */
  6. function array_sort($ array_name,$row_id,$order_type){
  7. $array_temp=array();
  8. foreach($array_name as $key=>$value){//Loop one level;
  9. $array_temp[$key]=$value[$ row_id];//Create a new one-dimensional array, the index value uses the index value of the two-dimensional array; the value is the value of the item to be compared in the two-dimensional array;
  10. }
  11. if ($order_type==="ASC"){
  12. asort($array_temp);
  13. }else{
  14. arsort($array_temp);
  15. }
  16. $result_array=array();
  17. foreach($array_temp as $key=>$value){//Filtered array Traverse;
  18. $result_array[]=$array_name[$key];//Create a new result array, change the key value order of the original array and assign it to the result array (the original array remains unchanged);
  19. }
  20. return $result_array ;
  21. }
  22. //The following is the test
  23. $arr=array(array('num'=>7,'value'=>4),
  24. array('num'=>3,'value'=> ;45),
  25. array('num'=>38,'value'=>27));
  26. $sortarr=array_sort($arr,'value','ASC');
  27. print_r($sortarr);
  28. ?>
Copy code


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template