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

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

程序员文章站 2024-01-19 18:50:16
复制代码 代码如下:
复制代码 代码如下:

<?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[] = '$'.$arg;
}
else
{
$sortrule[] = $arg;
}
}
foreach($arraydata as $key => $info)
{
foreach($keynamelist as $keyname)
{
${$keyname}[$key] = $info[$keyname];
}
}
$evalstring = 'array_multisort('.join(",",$sortrule).',$arraydata);';
eval ($evalstring);
return $arraydata;
}
//################# 示例 #################
$arr = array(
array(
'name' => '学习',
'size' => '1235',
'type' => 'jpe',
'time' => '1921-11-13',
'class' => 'd',
),
array(
'name' => '中国功夫',
'size' => '153',
'type' => 'jpe',
'time' => '2005-11-13',
'class' => 'j',
),
array(
'name' => '编程',
'size' => '35',
'type' => 'gif',
'time' => '1997-11-13',
'class' => 'a',
),
array(
'name' => '中国功夫',
'size' => '65',
'type' => 'jpe',
'time' => '1925-02-13',
'class' => 'd',
),
array(
'name' => '中国功夫',
'size' => '5',
'type' => 'icon',
'time' => '1967-12-13',
'class' => 'c',
),
);
print_r($arr);
//注意:按照数字方式排序时 153 比 65 小
$temp = syssortarray($arr,"class","sort_asc","type","sort_desc","size","sort_asc","sort_string");
echo "<pre>";
print_r($temp);
?>