Blogger Information
Blog 10
fans 0
comment 0
visits 6997
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
一维数组排序,保留key值
礼物粑粑
Original
781 people have browsed it

话不多说,直接上代码

  1. function sortWithKeyName($arr, $orderBy = 'desc')
  2. {
  3. //在内存的另一处 $a 复制内容与 $arr 一样的数组
  4. foreach ($arr as $key => $value)
  5. $a[$key] = $value;
  6. if ($orderBy == 'asc') {//对数组 $arr 进行排序
  7. asort($arr);
  8. } else {
  9. arsort($arr);
  10. }
  11. /*创建一个以原始数组的键名为元素值 (键值) 的
  12. *数组 $b, 其元素 (键值) 顺序,与排好序的数组 $arr 一致。
  13. */
  14. $index = 0;
  15. foreach ($arr as $keys => $values) //按排序后数组的顺序
  16. foreach ($a as $key => $value) //在备份数组中寻找键值
  17. if ($values == $value)//如果找到键值
  18. $b[$index++] = $key; // 则将数组 $b 的元素值,设置成备份数组 $a 的键名
  19. //返回用数组 $b 的键值作为键名,数组 $arr 的键值作为键值,所组成的数组
  20. return array_combine($b, $arr);
  21. }
  22. //$arr = array('AA'=>3,'AB'=>1,'AC'=>2);
  23. //排序 123 保留 AA,AB,AC
  24. private function sortWithKeyName($arr, $orderBy = 'desc')
  25. {
  26. $new_array = array();
  27. $new_sort = array();
  28. foreach ($arr as $key => $value) {
  29. $new_array[] = $value;
  30. }
  31. if ($orderBy == 'asc') {
  32. asort($new_array);
  33. } else {
  34. arsort($new_array);
  35. }
  36. foreach ($new_array as $k => $v) {
  37. foreach ($arr as $key => $value) {
  38. if ($v == $value) {
  39. $new_sort[$key] = $value;
  40. unset($arr[$key]);
  41. break;
  42. }
  43. }
  44. }
  45. return $new_sort;
  46. }
  47. 参考了https://www.cnblogs.com/zengdiao/p/6019290.html
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post