-3

我有这个数组:

$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");

我该怎么做?

4

4 回答 4

2

在这里扩展马克贝克的评论:

$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
)

演示!

于 2013-10-11T13:08:53.653 回答
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);
于 2013-10-11T13:09:06.290 回答
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];
于 2013-10-11T13:13:25.260 回答
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

于 2013-10-11T13:20:17.363 回答