首页 >后端开发 >php教程 >PHP排序之二维数组的按照字母排序实现代码

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

高洛峰
高洛峰原创
2016-12-22 11:24:161408浏览

<?php 
/** 
* Sort an two-dimension array by some level two items use array_multisort() function. 
* 
* sysSortArray($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2"……) 
* @author Chunsheng Wang <wwccss@263.net> 
* @param array $ArrayData the array to sort. 
* @param string $KeyName1 the first item to sort by. 
* @param string $SortOrder1 the order to sort by("SORT_ASC"|"SORT_DESC") 
* @param string $SortType1 the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING") 
* @return array sorted array. 
*/ 
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR") 
{ 
if(!is_array($ArrayData)) 
{ 
return $ArrayData; 
} 
$ArgCount = func_num_args(); 
for($I = 1;$I < $ArgCount;$I ++) 
{ 
$Arg = func_get_arg($I); 
if(!eregi("SORT",$Arg)) 
{ 
$KeyNameList[] = $Arg; 
$SortRule[] = &#39;$&#39;.$Arg; 
} 
else 
{ 
$SortRule[] = $Arg; 
} 
} 
foreach($ArrayData AS $Key => $Info) 
{ 
foreach($KeyNameList AS $KeyName) 
{ 
${$KeyName}[$Key] = $Info[$KeyName]; 
} 
} 
$EvalString = &#39;array_multisort(&#39;.join(",",$SortRule).&#39;,$ArrayData);&#39;; 
eval ($EvalString); 
return $ArrayData; 
} 
//################# 示例 ################# 
$arr = array( 
array( 
&#39;name&#39; => &#39;学习&#39;, 
&#39;size&#39; => &#39;1235&#39;, 
&#39;type&#39; => &#39;jpe&#39;, 
&#39;time&#39; => &#39;1921-11-13&#39;, 
&#39;class&#39; => &#39;D&#39;, 
), 
array( 
&#39;name&#39; => &#39;中国功夫&#39;, 
&#39;size&#39; => &#39;153&#39;, 
&#39;type&#39; => &#39;jpe&#39;, 
&#39;time&#39; => &#39;2005-11-13&#39;, 
&#39;class&#39; => &#39;J&#39;, 
), 
array( 
&#39;name&#39; => &#39;编程&#39;, 
&#39;size&#39; => &#39;35&#39;, 
&#39;type&#39; => &#39;gif&#39;, 
&#39;time&#39; => &#39;1997-11-13&#39;, 
&#39;class&#39; => &#39;A&#39;, 
), 
array( 
&#39;name&#39; => &#39;中国功夫&#39;, 
&#39;size&#39; => &#39;65&#39;, 
&#39;type&#39; => &#39;jpe&#39;, 
&#39;time&#39; => &#39;1925-02-13&#39;, 
&#39;class&#39; => &#39;D&#39;, 
), 
array( 
&#39;name&#39; => &#39;中国功夫&#39;, 
&#39;size&#39; => &#39;5&#39;, 
&#39;type&#39; => &#39;icon&#39;, 
&#39;time&#39; => &#39;1967-12-13&#39;, 
&#39;class&#39; => &#39;C&#39;, 
), 
); 
print_r($arr); 
//注意:按照数字方式排序时 153 比 65 小 
$temp = sysSortArray($arr,"class","SORT_ASC","type","SORT_DESC","size","SORT_ASC","SORT_STRING"); 
echo "<pre class="brush:php;toolbar:false">"; 
print_r($temp); 
?>


更多PHP排序之二维数组的按照字母排序实现代码相关文章请关注PHP中文网!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn