如何将php关联数组排序为特定顺序? [英] How to sort a php associative array to a specific order?
本文介绍了如何将php关联数组排序为特定顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我要按特定顺序排序的数组
this is the array i like to sort in a particular order
$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代码
for this I am trying the following php code
$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);
推荐答案
Easy- 只需使用 arraySort
作为assoc键并获取原始数组中对应的数组/值
Easy- Just use the arraySort
as the assoc key and get the corresponding array / value from the original array,
<?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);
这篇关于如何将php关联数组排序为特定顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文