当前位置:Gxlcms > PHP教程 > php二维数组排序示例

php二维数组排序示例

时间:2021-07-01 10:21:17 帮助过:6人阅读

例子,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 < $ArgCount;$I ++)
  28. {
  29. $Arg = func_get_arg($I);
  30. if(!eregi("SORT",$Arg))
  31. {
  32. $KeyNameList[] = $Arg;
  33. $SortRule[] = '$'.$Arg;
  34. }
  35. else
  36. {
  37. $SortRule[] = $Arg;
  38. }
  39. }
  40. // Get the values according to the keys and put them to array.
  41. foreach($ArrayData AS $Key => $Info)
  42. {
  43. foreach($KeyNameList AS $KeyName)
  44. {
  45. ${$KeyName}[$Key] = $Info[$KeyName];
  46. }
  47. }
  48. // Create the eval string and eval it.
  49. $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
  50. eval ($EvalString);
  51. return $ArrayData;
  52. }
  53. //################# 示例 #################
  54. $arr = array(
  55. array(
  56. 'name' => '学习',
  57. 'size' => '1235',
  58. 'type' => 'jpe',
  59. 'time' => '1921-11-13',
  60. 'class' => 'dd',
  61. ),
  62. array(
  63. 'name' => '中国功夫',
  64. 'size' => '153',
  65. 'type' => 'jpe',
  66. 'time' => '2005-11-13',
  67. 'class' => 'jj',
  68. ),
  69. array(
  70. 'name' => '编程',
  71. 'size' => '35',
  72. 'type' => 'gif',
  73. 'time' => '1997-11-13',
  74. 'class' => 'dd',
  75. ),
  76. array(
  77. 'name' => '中国功夫',
  78. 'size' => '65',
  79. 'type' => 'jpe',
  80. 'time' => '1925-02-13',
  81. 'class' => 'yy',
  82. ),
  83. array(
  84. 'name' => '中国功夫',
  85. 'size' => '5',
  86. 'type' => 'icon',
  87. 'time' => '1967-12-13',
  88. 'class' => 'rr',
  89. ),
  90. );
  91. print_r($arr);
  92. //注意:按照数字方式排序时 153 比 65 小
  93. $temp = sysSortArray($arr,"name","SORT_ASC","type","SORT_DESC","size","SORT_ASC","SORT_STRING");
  94. print_r($temp);
  95. ?>

人气教程排行