这是我想按特定顺序排序的数组
$aData = Array
(
[break] => Array
(
[Indoor room] => 42
[Gym Class] => 19
)
[finish] => Array
(
[Indoor room] => 42
[Gym Class] => 19
)
[lunch] => Array
(
[Indoor room] => 7
)
[period1] => Array
(
[Indoor room] => 12
[Gym Class] => 22
)
[period2] => Array
(
[Gym Class] => 14
[Indoor room] => 25
)
[period3] => Array
(
[Gym Class] => 21
[Indoor room] => 11
)
[period4] => Array
(
[Gym Class] => 22
[Indoor room] => 20
)
[period5] => Array
(
[Gym Class] => 16
[Indoor room] => 9
)
)
但我喜欢这个顺序:
break, period1, period2, lunch, period3, period5, period6, finish
为此我尝试以下PHP代码
$arraySort = [
"break",
"period1",
"period2",
"period3",
"lunch",
"period4",
"period5",
"period6",
"finish"
];
foreach($aData as $period => $catsScore){
echo 'test '.$period.'<br/>';
$periodItem = [$period];
foreach($arraySort as $cat){
echo 'new: '.$cat.'<br/>';
$periodItem[] = $catsScore;
}
$output[] = $periodItem;
}
print_r($output);
答案 0 :(得分:2)
简单 - 只需使用arraySort
作为关键字,并从原始数组中获取相应的数组/值,
<?php
$arraySort = [
"break",
"period1",
"period2",
"period3",
"lunch",
"period4",
"period5",
"period6",
"finish"
];
$final_array = [];
foreach($arraySort as $arraySo){
$final_array[$arraySo] = $aData[$arraySo];
}
print_r($final_array);
输出: - https://eval.in/926361
答案 1 :(得分:1)
答案 2 :(得分:1)
或者您可以使用实际排序功能:
uksort(
$aData,
function($a,$b)use($arraySort){
return array_search($a, $arraySort) - array_search($b, $arraySort);
}
);
答案 3 :(得分:0)
您可以将array_combine
用于此目的:
$arrary_sort = ["break", "period1"];
$final_array = array_combine($array_sort, $your_array_here);