使用以下内容按屏幕名称对多维数组进行排序:
$sortArray = array();
foreach($members as $member){
foreach($member as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "screen_name";
array_multisort($sortArray[$orderby],SORT_ASC,$members);
但大写字母在小写之前排序:
阿伦 布伦达 Greg 有效
但 Frank 出现在 dan
之前排序数组有很多,但我终于使用上面的工作了,想看看是否有一种简单的方法来修复它?
答案 0 :(得分:1)
uasort()应该适合你
<?php
// custom sort function
function sort_by_screen_name($a, $b) {
// compare using lowercase strings only
$a = strtolower($a['screen_name']);
$b = strtolower($b['screen_name']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$members = array(
array('screen_name'=>'Greg'),
array('screen_name'=>'Allen'),
array('screen_name'=>'dan'),
array('screen_name'=>'Brenda'),
);
// uasort() like a boss!
uasort($members, 'sort_by_screen_name');
print_r($members);
输出
Array
(
[1] => Array
(
[screen_name] => Allen
)
[3] => Array
(
[screen_name] => Brenda
)
[2] => Array
(
[screen_name] => dan
)
[0] => Array
(
[screen_name] => Greg
)
)
注意:使用此方法保留原始数组键。如果您想要重写密钥,只需使用usort()
。
答案 1 :(得分:1)
您可以使用usort()
和自定义排序功能对此进行排序。如果您想了解它如何适合您自己的自定义详细信息,则可以修改此数据:http://codepad.org/b89HwmbM
$members = array(
array( "loc" => "Ontario", "first" => "Bob", "screen_name" => "fooArt" ),
array( "loc" => "Atlanta", "first" => "Sal", "screen_name" => "TIMMY!" ),
array( "loc" => "Panama", "first" => "Mick", "screen_name" => "Analog" ),
array( "loc" => "Pensacola", "first" => "A", "screen_name" => "Franky" ),
array( "loc" => "McPherson", "first" => "Anna", "screen_name" => "annie9" )
);
usort( $members, 'custom_sort' );
function custom_sort( $m1, $m2 ){
return strtolower( $m1['screen_name'] ) > strtolower( $m2['screen_name'] );
};
此排序方法的输出如下:
Array
(
[0] => Array
(
[loc] => Panama
[first] => Mick
[screen_name] => Analog
)
[1] => Array
(
[loc] => McPherson
[first] => Anna
[screen_name] => annie_23
)
[2] => Array
(
[loc] => Ontario
[first] => Bob
[screen_name] => fooArt
)
[3] => Array
(
[loc] => Pensacola
[first] => A
[screen_name] => Franky
)
[4] => Array
(
[loc] => Atlanta
[first] => Sal
[screen_name] => TIMMY!
)
)