我试图理清单个数组的序列。如何使用我的另一个数组列表?
有一个预定义的数组:
$sortOrder = array("Night","Breakfast","Lunch","Dinner","Lying");
这就是我原来的数组内容:
Array
(
[Normal] => Array
(
[Dinner] => Array
(
[avgtime] => 17,06
[avg] => 5.24
)
[Breakfast] => Array
(
[avgtime] => 04,25
[avg] => 4.96
)
[Lying] => Array
(
[avgtime] => 14,49
[avg] => 4.7
)
[Lunch] => Array
(
[avgtime] => 09,53
[avg] => 5.26
)
[Night] => Array
(
[avgtime] => 00,00
[avg] => 4.4
)
)
[High] => Array
(
[Dinner] => Array
(
[avg] => 9
[avgtime] => 17,35
)
)
[Low] => Array
(
[Night] => Array
(
[avg] => 3.5
[avgtime] => 02,35
)
[Breakfast] => Array
(
[avg] => 3.8
[avgtime] => 07,12
)
)
)
如何根据列表订购?请帮助我,非常感谢!
答案 0 :(得分:0)
使用uksort,
的解决方案$temp = array ('Lunch'=>'3', 'Lying' => '5', 'Night' => '1', 'Dinner' => '4', 'Breakfast' => '2');
function cmp($a, $b) {
$sortOrder = array("Night","Breakfast","Lunch","Dinner","Lying");
$pos1 = array_search($a, $sortOrder);
$pos2 = array_search($b, $sortOrder);
if (pos1 == pos2) return 0;
return ($pos1 > $pos2)? 1:-1;
}
uksort($temp, 'cmp');
// output: Array ( [Night] => 1 [Breakfast] => 2 [Lunch] => 3 [Dinner] => 4 [Lying] => 5 )
答案 1 :(得分:0)
为了实现更有效的密钥搜索,我们在比较函数中使用静态数组:
foreach ($arr as $key => $row) {
uksort($arr[$key], function($a, $b) {
static $sortOrder = ['Night', 'Breakfast', 'Lunch', 'Dinner', 'Lying'];
static $order;
if (!isset($order)) {
$order = array_flip($sortOrder);
}
$value = 0;
if (array_key_exists($a, $order) && array_key_exists($b, $order)) {
$value = ($order[$a] > $order[$b] ? 1 : -1);
}
return $value;
});
}