我有一個 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 關注
- 138 瀏覽
添加回答
舉報
0/150
提交
取消