我有一个非常大的数组包含以下数据:
Array
(
[2] => Array
(
[Berlin] => Array
(
[1] => Array
(
[0] => stdClass Object
(
[name] => Joe
[car_name] => Audi
[car_color] => Black
[sid] => 130
)
[1] => stdClass Object
(
[name] => Mark
[car_name] => BMW
[car_color] => Red
[sid] => 135
)
)
[0] => Array
(
[0] => stdClass Object
(
[name] => Lucas
[car_name] => Audi
[car_color] => Yellow
[sid] => 168
)
[1] => stdClass Object
(
[name] => Joe
[car_name] => Volkswagen
[car_color] => Black
[sid] => 170
)
[2] => stdClass Object
(
[name] => Thomas
[car_name] => Ford
[car_color] => Gray
[sid] => 119
)
)
)
[Moscow] => Array
(
[1] => Array
(
[0] => stdClass Object
(
[name] => Matt
[car_name] => Mustang
[car_color] => Black
[sid] => 230
)
[1] => stdClass Object
(
[name] => Suze
[car_name] => Lada
[car_color] => Red
[sid] => 245
)
)
[0] => Array
(
[0] => stdClass Object
(
[name] => Lucas
[car_name] => Unknown
[car_color] => Brown
[sid] => 374
)
[1] => stdClass Object
(
[name] => Mathew
[car_name] => Volkswagen
[car_color] => Blue
[sid] => 589
)
[2] => stdClass Object
(
[name] => Thomas
[car_name] => Ford
[car_color] => Light Blue
[sid] => 741
)
)
)
)
)
现在我想这样排序(请阅读//
行):
Array
(
[2] => Array //from min to max - eg. from 0 to 50
(
[Berlin] => Array //alphabetically from A to Z
(
[1] => Array //from min to max eg. from 0 to 1
(
)
)
)
)
我如何在PHP中实现这一目标?我希望我很清楚,随时可以在评论中询问其他信息。
答案 0 :(得分:5)
会是这样的:
// ksort sorts the keys low to high
ksort($array[2]);
// uksort w/ natsort is a full alphanumeric sorting A-Z0-9
uksort($array[2]['Berlin'], 'natsort');
ksort($array[2]['Berlin'][1]);
有关数组和数组函数的文档:
http://us3.php.net/manual/en/book.array.php
功能示例
此示例特定于您的示例;但是,如果您的数组结构非常动态,则可以创建递归样式函数。
$BigArray = array();
//Sorting the initial array index
ksort($BigArray);
foreach($BigArray as $a)
{
// Sorting Berlin / Moscow here..
uksort($a, 'natsort');
foreach($a as $b)
{
// Sorting the index inside the cities
ksort($b);
}
}
答案 1 :(得分:1)
最紧凑的方法是使用递归函数。这也允许您在代码中其他位置的不同维度的数组上重用它。
function SortArray($arr) {
if(!is_array($InnerArray))
return;
foreach($arr as $InnerArray) {
SortArray($InnerArray);
}
ksort($arr);
}
SortArray($array);