欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php二维数组排序示例

程序员文章站 2022-03-13 22:14:08
...

例子,php二维数组排序代码。

  1. // 说明:PHP中二维数组的排序方法
  2. // 整理:http://bbs.it-home.org
  3. /**
  4. * @package BugFree
  5. * @version $Id: FunctionsMain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss Exp $
  6. *
  7. *
  8. * Sort an two-dimension array by some level two items use array_multisort() function.
  9. *
  10. * sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2"……)
  11. * @author Chunsheng Wang
  12. * @param array $ArrayData the array to sort.
  13. * @param string $KeyName1 the first item to sort by.
  14. * @param string $SortOrder1 the order to sort by("SORT_ASC"|"SORT_DESC")
  15. * @param string $SortType1 the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
  16. * @return array sorted array.
  17. */
  18. function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
  19. {
  20. if(!is_array($ArrayData))
  21. {
  22. return $ArrayData;
  23. }
  24. // Get args number.
  25. $ArgCount = func_num_args();
  26. // Get keys to sort by and put them to SortRule array.
  27. for($I = 1;$I {
  28. $Arg = func_get_arg($I);
  29. if(!eregi("SORT",$Arg))
  30. {
  31. $KeyNameList[] = $Arg;
  32. $SortRule[] = '$'.$Arg;
  33. }
  34. else
  35. {
  36. $SortRule[] = $Arg;
  37. }
  38. }
  39. // Get the values according to the keys and put them to array.
  40. foreach($ArrayData AS $Key => $Info)
  41. {
  42. foreach($KeyNameList AS $KeyName)
  43. {
  44. ${$KeyName}[$Key] = $Info[$KeyName];
  45. }
  46. }
  47. // Create the eval string and eval it.
  48. $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
  49. eval ($EvalString);
  50. return $ArrayData;
  51. }
  52. //################# 示例 #################
  53. $arr = array(
  54. array(
  55. 'name' => '学习',
  56. 'size' => '1235',
  57. 'type' => 'jpe',
  58. 'time' => '1921-11-13',
  59. 'class' => 'dd',
  60. ),
  61. array(
  62. 'name' => '中国功夫',
  63. 'size' => '153',
  64. 'type' => 'jpe',
  65. 'time' => '2005-11-13',
  66. 'class' => 'jj',
  67. ),
  68. array(
  69. 'name' => '编程',
  70. 'size' => '35',
  71. 'type' => 'gif',
  72. 'time' => '1997-11-13',
  73. 'class' => 'dd',
  74. ),
  75. array(
  76. 'name' => '中国功夫',
  77. 'size' => '65',
  78. 'type' => 'jpe',
  79. 'time' => '1925-02-13',
  80. 'class' => 'yy',
  81. ),
  82. array(
  83. 'name' => '中国功夫',
  84. 'size' => '5',
  85. 'type' => 'icon',
  86. 'time' => '1967-12-13',
  87. 'class' => 'rr',
  88. ),
  89. );
  90. print_r($arr);
  91. //注意:按照数字方式排序时 153 比 65 小
  92. $temp = sysSortArray($arr,"name","SORT_ASC","type","SORT_DESC","size","SORT_ASC","SORT_STRING");
  93. print_r($temp);
  94. ?>
复制代码