见演示:http ://codepad.org/vDI2k4n6
$arrayMonths = array(
'jan' => array(1, 8, 5,4),
'feb' => array(10,12,15,11),
'mar' => array(12, 7, 4, 3),
'apr' => array(10,16,7,17),
);
$position = array("Foo1","Foo2","Foo3","FooN");
$set = array();
foreach($arrayMonths as $key => $value)
{
$max = max($value);
$pos = array_search($max, $value);
$set[$key][$position[$pos]] = $max ;
}
function cmp($a, $b)
{
foreach($a as $key => $value )
{
foreach ($b as $bKey => $bValue)
{
return $bValue - $value ;
}
}
}
uasort($set,"cmp");
var_dump($set);
输出
array
'apr' =>
array
'FooN' => int 17
'feb' =>
array
'Foo3' => int 15
'mar' =>
array
'Foo1' => int 12
'jan' =>
array
'Foo2' => int 8
另一个例子:-
使用 PHP 对多维数组进行排序
http://www.firsttube.com/read/sorting-a-multi-dimensional-array-with-php/
每隔一段时间,我就会发现自己有一个多维数组,我想按子数组中的值对其进行排序。我有一个可能看起来像这样的数组:
//an array of some songs I like
$songs = array(
'1' => array('artist'=>'The Smashing Pumpkins', 'songname'=>'Soma'),
'2' => array('artist'=>'The Decemberists', 'songname'=>'The Island'),
'3' => array('artist'=>'Fleetwood Mac', 'songname' =>'Second-hand News')
);
问题是这样的:我想以“歌曲名(艺术家)”的格式回显我喜欢的歌曲,并且我想按艺术家的字母顺序来做。PHP 提供了许多用于对数组进行排序的函数,但没有一个可以在这里工作。ksort() 将允许我按键排序,但 $songs 数组中的键无关紧要。asort() 允许我对键进行排序和保留,但它会根据每个元素的值对 $songs 进行排序,这也是无用的,因为每个元素的值都是“array()”。usort() 是另一种可能的候选方法,可以进行多维排序,但它涉及构建回调函数,并且通常很冗长。甚至 PHP 文档中的示例也引用了特定的键。
所以我开发了一个快速函数来按子数组中键的值进行排序。请注意,此版本不区分大小写。请参阅下面的 subval_sort()。
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
要在上面使用它,我只需键入:
$songs = subval_sort($songs,'artist');
print_r($songs);
这是您应该期望看到的:
Array
(
[0] => Array
(
[artist] => Fleetwood Mac
[song] => Second-hand News
)
[1] => Array
(
[artist] => The Decemberists
[song] => The Island
)
[2] => Array
(
[artist] => The Smashing Pumpkins
[song] => Cherub Rock
)
)
歌曲,按艺术家排序。