我有一个 php 国家/地区数组,我希望根据客户的要求将其按特定顺序排序。该数组目前是从我们的后端馈入的,我无法控制,如下所示: array(10) { ["AUD"]=> string(17) "Australian Dollar" ["GBP"]=> string(22) "British Pound Sterling" ["CAD"]=> string(15) "Canadian Dollar" ["DKK"]=> string(12) "Danish Krone" ["EUR"]=> string(4) "Euro" ["JPY"]=> string(12) "Japanese Yen" ["NOK"]=> string(15) "Norwegian Krone" ["RUB"]=> string(13) "Russian Ruble" ["SEK"]=> string(13) "Swedish Krona" ["USD"]=> string(9) "US Dollar"}我需要根据客户偏好重新排序 array(10) { ["GBP"]=> string(22) "British Pound Sterling" ["AUD"]=> string(17) "Australian Dollar" ["NOK"]=> string(15) "Norwegian Krone" ["RUB"]=> string(13) "Russian Ruble" ["USD"]=> string(9) "US Dollar" ["CAD"]=> string(15) "Canadian Dollar" ["DKK"]=> string(12) "Danish Krone" ["EUR"]=> string(4) "Euro" ["JPY"]=> string(12) "Japanese Yen" ["SEK"]=> string(13) "Swedish Krona"}我能想到的唯一方法是使用 switch 语句, $ordered_currencies = Array(); ?> <?php foreach ($currencies as $_code => $_name): switch ($_code) { case 'AUD': $ordered_currencies[0] = [$_code => $_name]; break; case 'CAD': $ordered_currencies[1] = Array($_code => $_name); break; case 'GBP': $ordered_currencies[2] = Array($_code => $_name); break; case 'DKK': $ordered_currencies[3] = Array($_code => $_name); break; case 'EUR': $ordered_currencies[4] = Array($_code => $_name); break; case 'JPY': $ordered_currencies[5] = Array($_code => $_name); break; case 'RUB': $ordered_currencies[6] = Array($_code => $_name); break; case 'SEK':
1 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
您可以将客户端首选项存储为货币代码数组,并$currencies按照此首选项数组的顺序获取值:
$preferences = ['AUD', 'CAD', 'GBP'];
$sortedCurrencies = [];
foreach ($preferences as $preference) {
$sortedCurrencies[$preference] = $currencies[$preference];
}
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报
0/150
提交
取消