设为首页收藏本站

PHP开源论坛

 找回密码
 注册

人人连接登陆

无需注册,直接登录

用新浪微博连接

一步搞定

QQ登录

只需一步,快速开始

查看: 1940|回复: 0

PHP中二维数组的排序方法  关闭 [复制链接]

Rank: 7Rank: 7Rank: 7

发表于 2008-12-5 18:18:21 |显示全部楼层
本文介绍的是从 BugFree 摘录来的二维数组排序函数,可以实现类似 MySQL 的 ORDER BY 效果,当数组不是从数据库取得时会有特殊应用。

  1. // 说明:PHP中二维数组的排序方法
  2. // 整理:http://www.CodeBit.cn

  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 <wwccss@263.net>
  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. if (! is_array ( $ArrayData )) {
  20.   return $ArrayData;
  21. }

  22. // Get args number.
  23. $ArgCount = func_num_args ();

  24. // Get keys to sort by and put them to SortRule array.
  25. for($I = 1; $I < $ArgCount; $I ++) {
  26.   $Arg = func_get_arg ( $I );
  27.   if (! eregi ( "SORT", $Arg )) {
  28.    $KeyNameList [] = $Arg;
  29.    $SortRule [] = '$' . $Arg;
  30.   } else {
  31.    $SortRule [] = $Arg;
  32.   }
  33. }

  34. // Get the values according to the keys and put them to array.
  35. foreach ( $ArrayData as $Key => $Info ) {
  36.   foreach ( $KeyNameList as $KeyName ) {
  37.    ${$KeyName} [$Key] = $Info [$KeyName];
  38.   }
  39. }

  40. // Create the eval string and eval it.
  41. $EvalString = 'array_multisort(' . join ( ",", $SortRule ) . ',$ArrayData);';
  42. eval ( $EvalString );
  43. return $ArrayData;
  44. }
  45. //################# 示例 ################
  46. $arr = array (array ('name' => '学习', 'size' => '1235', 'type' => 'jpe', 'time' => '1921-11-13', 'class' => 'dd' ), array ('name' => '中国功夫', 'size' => '153', 'type' => 'jpe', 'time' => '2005-11-13', 'class' => 'jj' ), array ('name' => '编程', 'size' => '35', 'type' => 'gif', 'time' => '1997-11-13', 'class' => 'dd' ), array ('name' => '中国功夫', 'size' => '65', 'type' => 'jpe', 'time' => '1925-02-13', 'class' => 'yy' ), array ('name' => '中国功夫', 'size' => '5', 'type' => 'icon', 'time' => '1967-12-13', 'class' => 'rr' ) );
  47. print_r ( $arr );
  48. //注意:按照数字方式排序时 153 比 65 小
  49. $temp = sysSortArray ( $arr, "name", "SORT_ASC", "type", "SORT_DESC", "size", "SORT_ASC", "SORT_STRING" );
  50. print_r ( $temp );
复制代码
PHP开源网:http://www.php-open.org

使用道具 举报

您需要登录后才可以回帖 登录 | 注册 人人连接登陆

Archiver|手机版|PHP开源网 ( 豫ICP备08005353号 )   

GMT+8, 2012-5-21 03:05

Powered by Discuz! X2

© 2001-2011 Comsenz Inc.

回顶部