本文實例講述了php自定義二維數(shù)組排序函數(shù)array_orderby用法。分享給大家供大家參考,具體如下:
?php
/**
I came up with an easy way to sort database-style results. This does what example 3 does, except it takes care of creating those intermediate arrays for you before passing control on to array_multisort().
*/
function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = $data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
/*
The sorted array is now in the return value of the function instead of being passed by reference.
*/
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
// Pass the array, followed by the column names and sort flags
$sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
print_r($sorted)
?>
運行結(jié)果:
Array
(
[0] => Array
(
[volume] => 98
[edition] => 2
)
[1] => Array
(
[volume] => 86
[edition] => 1
)
[2] => Array
(
[volume] => 86
[edition] => 6
)
[3] => Array
(
[volume] => 85
[edition] => 6
)
[4] => Array
(
[volume] => 67
[edition] => 2
)
[5] => Array
(
[volume] => 67
[edition] => 7
)
)
PS:這里再為大家推薦一款關(guān)于排序的演示工具供大家參考:
在線動畫演示插入/選擇/冒泡/歸并/希爾/快速排序算法過程工具:
http://tools.jb51.net/aideddesign/paixu_ys
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學(xué)運算技巧總結(jié)》
希望本文所述對大家PHP程序設(shè)計有所幫助。
您可能感興趣的文章:- php自定義排序uasort函數(shù)示例【二維數(shù)組按指定鍵值排序】
- PHP自定義遞歸函數(shù)實現(xiàn)數(shù)組轉(zhuǎn)JSON功能【支持GBK編碼】
- PHP自定義函數(shù)實現(xiàn)assign()數(shù)組分配到模板及extract()變量分配到模板功能示例
- PHP自定義函數(shù)實現(xiàn)數(shù)組比較功能示例
- PHP判斷函數(shù)是否被定義的方法