Discuz教程网

PHP排序之二维数组的按照字母排序实现代码

[复制链接]
authicon dly 发表于 2011-8-31 11:09:30 | 显示全部楼层 |阅读模式
代码如下:

  1. <?php
  2. /**
  3. * Sort an two-dimension array by some level two items use array_multisort() function.
  4. *
  5. * sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2"……)
  6. * @author Chunsheng Wang <wwccss@263.net>
  7. * @param array $ArrayData the array to sort.
  8. * @param string $KeyName1 the first item to sort by.
  9. * @param string $SortOrder1 the order to sort by("SORT_ASC"|"SORT_DESC")
  10. * @param string $SortType1 the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
  11. * @return array sorted array.
  12. */
  13. function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
  14. {
  15. if(!is_array($ArrayData))
  16. {
  17. return $ArrayData;
  18. }
  19. $ArgCount = func_num_args();
  20. for($I = 1;$I < $ArgCount;$I ++)
  21. {
  22. $Arg = func_get_arg($I);
  23. if(!eregi("SORT",$Arg))
  24. {
  25. $KeyNameList[] = $Arg;
  26. $SortRule[] = '$'.$Arg;
  27. }
  28. else
  29. {
  30. $SortRule[] = $Arg;
  31. }
  32. }
  33. foreach($ArrayData AS $Key => $Info)
  34. {
  35. foreach($KeyNameList AS $KeyName)
  36. {
  37. ${$KeyName}[$Key] = $Info[$KeyName];
  38. }
  39. }
  40. $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
  41. eval ($EvalString);
  42. return $ArrayData;
  43. }
  44. //################# 示例 #################
  45. $arr = array(
  46. array(
  47. 'name' => '学习',
  48. 'size' => '1235',
  49. 'type' => 'jpe',
  50. 'time' => '1921-11-13',
  51. 'class' => 'D',
  52. ),
  53. array(
  54. 'name' => '中国功夫',
  55. 'size' => '153',
  56. 'type' => 'jpe',
  57. 'time' => '2005-11-13',
  58. 'class' => 'J',
  59. ),
  60. array(
  61. 'name' => '编程',
  62. 'size' => '35',
  63. 'type' => 'gif',
  64. 'time' => '1997-11-13',
  65. 'class' => 'A',
  66. ),
  67. array(
  68. 'name' => '中国功夫',
  69. 'size' => '65',
  70. 'type' => 'jpe',
  71. 'time' => '1925-02-13',
  72. 'class' => 'D',
  73. ),
  74. array(
  75. 'name' => '中国功夫',
  76. 'size' => '5',
  77. 'type' => 'icon',
  78. 'time' => '1967-12-13',
  79. 'class' => 'C',
  80. ),
  81. );
  82. print_r($arr);
  83. //注意:按照数字方式排序时 153 比 65 小
  84. $temp = sysSortArray($arr,"class","SORT_ASC","type","SORT_DESC","size","SORT_ASC","SORT_STRING");
  85. echo "<pre>";
  86. print_r($temp);
  87. ?>
复制代码








上一篇:PHP程序的国际化实现方法(利用gettext)
下一篇:不支持fsockopen但支持culr环境下下ucenter与modoer通讯问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-3 07:47

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表