我有以下数组:
Array ( [1] => Array ( [0] => Array ( [class] => Advanced Hip Hop Ages 10+ [session] => 0 [start] => 1436902200 [end] => 1436905800 [capacity] => [students] => 1 ) [1] => Array ( [class] => Intermediate Hip Hop Ages 9+ [session] => 0 [start] => 1436899500 [end] => 1436902200 [capacity] => [students] => 1 ) [2] => Array ( [class] => Beginning Pointe Ages 10+ [session] => 0 [start] => 1436896800 [end] => 1436899500 [capacity] => [students] => 1 ) [3] => Array ( [class] => Int/Adv Ballet Ages 10+ [session] => 0 [start] => 1436889600 [end] => 1436896800 [capacity] => 15 [students] => 1 ) [4] => Array ( [class] => Beginning Ballet 8+ year olds [session] => 0 [start] => 1436884200 [end] => 1436891400 [capacity] => 15 [students] => 1 ) ) [2] => Array ( [0] => Array ( [class] => Intermediate Technique/Progressions Ages 9+ [session] => 0 [start] => 1436899500 [end] => 1436904900 [capacity] => [students] => 1 ) [1] => Array ( [class] => Int/Adv Tap Ages 9+ [session] => 0 [start] => 1436895900 [end] => 1436899500 [capacity] => [students] => 1 ) [2] => Array ( [class] => Beginning Jazz/Contemporary Technique Ages 8+ [session] => 0 [start] => 1436887800 [end] => 1436893200 [capacity] => [students] => 1 ) ) [3] => Array ( [0] => Array ( [class] => Int/Adv Jazz 9+ [session] => 0 [start] => 1436893200 [end] => 1436898600 [capacity] => [students] => 1 ) [1] => Array ( [class] => Int/Adv Ballet Barre Ages 9+ [session] => 0 [start] => 1436886000 [end] => 1436889600 [capacity] => [students] => 1 ) ) )
I would like to sort the the third level of the array (the classes) by their start time. I have tried a number of different solutions suggested on here for two level arrays, to no avail.
My latest attempt is:
array_walk($schedule, 'walk_cmp');
function walk_cmp($array, $key){
usort($array, function($a, $b) {
return ($a['start'] > $b['start']) ? -1: 1;
});
}
我已经确认排序在 walk_cmp
中正常工作,但对数组的这些更改不会反射(reflect)在主数组中。
我觉得我一定错过了一些明显的东西,但我在这里。请记住,这是一个本质上是动态的示例数组。它将始终具有此结构,但第二个(Day)和第三个(Class)数组中的元素数量会有所不同。
最佳答案
您的尝试看起来不错,而且您也非常接近解决方案!
您的主要问题是,您将函数中的数组作为局部变量进行排序。所以你的原始数组不会改变。您必须传递数组 by reference.所以你的代码看起来像这样:
array_walk($schedule, "walk_cmp");
function walk_cmp(&$array, $key) {
//^ See here
uasort($array, function($a, $b) {
if($a['start'] == $b['start']) //If they are the same, return 0
return 0;
return ($a['start'] > $b['start']) ? -1 : 1;
});
}
关于php - 如何在 PHP 中使用 array_walk 对三维数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31443269/