php natsort,PHP: natsort - Manual

additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this:

$array['test0'] = array('main' =>  'a', 'sub' => 'a');

$array['test2'] = array('main' =>  'a', 'sub' => 'b');

$array['test3'] = array('main' =>  'b', 'sub' => 'c');

$array['test1'] = array('main' =>  'a', 'sub' => 'c');

$array['test4'] = array('main' =>  'b', 'sub' => 'a');

$array['test5'] = array('main' =>  'b', 'sub' => 'b');

?>

or

$array[0] = array('main' =>  1, 'sub' => 1);

$array[2] = array('main' =>  1, 'sub' => 2);

$array[3] = array('main' =>  2, 'sub' => 3);

$array[1] = array('main' =>  1, 'sub' => 3);

$array[4] = array('main' =>  2, 'sub' => 1);

$array[5] = array('main' =>  2, 'sub' => 2);

?>

on one or more columns.

the code

$array = array_natsort_list($array,'main','sub'); ?>

will result in $array being sortet like this:

test0,test2,test1,test4,test5,test3

or

0,2,1,4,5,3.

you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached.

to me it was very usefull for sorting a menu having submenus and even sub-submenus.

i hope it might help you too.

here is the function:

function array_natsort_list($array) {

// for all arguments without the first starting at end of list

for ($i=func_num_args();$i>1;$i--) {

// get column to sort by

$sort_by = func_get_arg($i-1);

// clear arrays

$new_array = array();

$temporary_array = array();

// walk through original array

foreach($array as $original_key => $original_value) {

// and save only values

$temporary_array[] = $original_value[$sort_by];

}

// sort array on values

natsort($temporary_array);

// delete double values

$temporary_array = array_unique($temporary_array);

// walk through temporary array

foreach($temporary_array as $temporary_value) {

// walk through original array

foreach($array as $original_key => $original_value) {

// and search for entries having the right value

if($temporary_value == $original_value[$sort_by]) {

// save in new array

$new_array[$original_key] = $original_value;

}

}

}

// update original array

$array = $new_array;

}

return $array;

}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值