您的位置:首页 > 其它

二维数组按照某个键值排序

2011-09-27 17:50 363 查看
//二维数组,按其中某个键值排序
/*
* @param array $array the array to sort.
* @param string $key_name the first item to sort by.
* @param string $sort_order the order to sort by("SORT_ASC"|"SORT_DESC")
* @param string $sort_type the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
*/
function multisort(&$array, $key_name, $sort_order = 'SORT_ASC', $sort_type = 'SORT_REGULAR') {
if (!is_array($array)) {
return $array;
}

// Get args number.
$arg_count = func_num_args();

// Get keys to sort by and put them to SortRule array.
for ($i = 1; $i < $arg_count; $i++) {
$arg = func_get_arg($i);
if (!eregi('SORT', $arg)) {
$key_name_list[] = $arg;
$sort_rule[] = '$'.$arg;
} else {
$sort_rule[] = $arg;
}
}

// Get the values according to the keys and put them to array.
foreach ($array as $key => $info) {
foreach ($key_name_list as $key_name) {
${$key_name}[$key] = $info[$key_name];
}
}

// Create the eval string and eval it.
$eval_str = 'array_multisort('.implode(',', $sort_rule).', $array);';
eval($eval_str);
return $array;

}


  例子

$data =  Array
(
0 => Array
(
'title' => '<font color="red">U8</font>-HR宁夏',
'linkline' => 'space.php?uid=4018&do=album&id=498',
'time' => 1275012236,
'content' => '<font color="red">U8</font>-HR宁夏',
'from' => 'album'
),
1 => Array
(
'title' => '<font color="red">u8</font> AII-in-One全国巡展-济宁站',
'linkline' => 'space.php?uid=2770&do=album&id=339',
'time' => 1268628887,
'content' => '<font color="red">u8</font> AII-in-One全国巡展-济宁站',
'from' => 'album'
),
2 => Array
(
'title' => '<font color="red">U8</font> ALL-IN-ONE巡展-河南站',
'linkline' => 'space.php?uid=1282&do=album&id=359',
'time' => 1269333609,
'content' => '<font color="red">U8</font> ALL-IN-ONE巡展-河南站',
'from' => 'album'
),
3 => Array
(
'title' => '先睹为快 <font color="red">U8</font> All-in-One体验光盘',
'linkline' => 'space.php?uid=3857&do=album&id=665',
'time' => 1285049939,
'content' => '先睹为快 <font color="red">U8</font> All-in-One体验光盘',
'from' => 'album'
)
)
multisort($data, 'time', 'SORT_DESC');


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐