我有这个数组:
$country_list =
array(
"AF" => "Afghanistan",
"AL" => "Albania",
"DZ" => "Algeria",
"AS" => "American Samoa",
"AD" => "Andorra",
"AO" => "Angola",
"AI" => "Anguilla",
"AQ" => "Antarctica",
"AG" => "Antigua and Barbuda",
..........
现在我从数据库中获取了密钥,但不知道有多少像:
$key='AL,AO,AG';
或
$key='AG,AD,AS,AQ,AF';
我想在第一个数组的数组中添加键和值,以使新数组如下所示:
$key =
array(
"AL" => "Albania",
"AO" => "Angola",
"AG" => "Antigua and Barbuda");
我该怎么做?
答案 0 :(得分:2)
扩展Mark Baker的评论here:
$key='AL,AO,AG';
$mykeys = array_flip(explode(',',$key));
$result = array_intersect_key($country_list, $mykeys);
print_r($result);
输出:
Array
(
[AL] => Albania
[AO] => Angola
[AG] => Antigua and Barbuda
)
答案 1 :(得分:1)
$country_list = array(
"AF" => "Afghanistan",
"AL" => "Albania",
"DZ" => "Algeria",
"AS" => "American Samoa",
"AD" => "Andorra",
"AO" => "Angola",
"AI" => "Anguilla",
"AQ" => "Antarctica",
"AG" => "Antigua and Barbuda",
...
);
$key='AL,AO,AG';
$subList = array_intersect_key(
$country_list,
array_flip(explode(',',$key))
);
var_dump($subList);
答案 2 :(得分:0)
$key='AL,AO,AG';
$key = explode(',',$key);
$key_array = array();
foreach($key as $k)
if (array_key_exists($k, $country_list))
$key_array[$k] = $country_list[$k];
答案 3 :(得分:0)
可以在数据库中保存名称和代码吗? 你的桌子应该是这样的
--------------
|code | name |
--------------
|AL | albania |
--------------
|AO | Angola |
--------------
|AG | Antigiua and Barbuda |
然后当你得到像
这样的代码$codes = 'AL,AO'
$codes2array = explode(',', $codes);
运行此sql
SELECT code, name FROM tbl_name WHERE code IN ("'.implode('","', $codes2array).'");
然后在不播放数组的情况下轻松选择名称
希望您找到我的解决方案
享受:D