我有一个国家/地区的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':
$ordered_currencies[7] = Array($_code => $_name);
break;
case 'USD':
$ordered_currencies[8] = Array($_code => $_name);
break;
}
endforeach; ?>
但这会返回以下格式的数组,这不是我所需要的
array(10) {
[0]=>
array(1) {
["AUD"]=>
string(17) "Australian Dollar"
}
[2]=>
array(1) {
["GBP"]=>
string(22) "British Pound Sterling"
}
[1]=>
array(1) {
["CAD"]=>
string(15) "Canadian Dollar"
}
.....
有什么想法吗?
答案 0 :(得分:1)
您可以将客户偏好设置存储为货币代码数组,并按照此偏好设置数组的顺序从$preferences = ['AUD', 'CAD', 'GBP'];
$sortedCurrencies = [];
foreach ($preferences as $preference) {
$sortedCurrencies[$preference] = $currencies[$preference];
}
中获取值:
if(head==NULL)
return 0;
while(head && fast->next!=NULL){
fast=fast->next->next;
}