使用jQuery从PHP关联数组中获取值

Chr*_*yne 5 javascript php jquery

我有一个从数组生成PHP的html选择元素,如下所示

$countries = array(
    array('iso' => 'AF', 'name' => 'Afghanistan',  'key' => 'Red'),
    array('iso' => 'AX', 'name' => 'Åland Islands','key' => 'Yellow'),
    array('iso' => 'AL', 'name' => 'Albania',      'key' => 'Blue')
);

$select = '<select id="country_select" onchange="countryfind()">';
foreach($countries as $country) {
    $select .= '<option value="'.$country['key'].'">'.$country['name'].'</option>';
}
$select = '</select>';

return $select;
Run Code Online (Sandbox Code Playgroud)

选择框使用小的javascript函数显示所选国家/地区的国家/地区密钥:

function countryfind(){
    jQuery('#countrykey').text(
         jQuery('#country_select option:selected').val()
)};
Run Code Online (Sandbox Code Playgroud)

我现在想使用该键与另一个包含有关国家/地区信息的PHP数组进行交互,并在#countrykey div中显示该国家/地区而不是所选值:

$si_federations = array(
    'Red'   => array('name'=>'A Red Country', 'url'=>'http://www.redcountry.com'),
    'Blue'   => array('name'=>'A Blue Country', 'url'=>'http://www.soroptimisteurope.org'),
);
Run Code Online (Sandbox Code Playgroud)

这是可以轻松实现的,还是我的方法完全错了?

Mac*_*ity 5

你在这里走在正确的轨道上。所以,这里是如何让它做你想做的事

在您的<script>块中,我们希望以 JSON 格式输出该数组

var federations = <?php echo json_encode($si_federations); ?>;
Run Code Online (Sandbox Code Playgroud)

现在,当您运行时,countryfind我们希望从该对象中提取值并同时显示它。所以让我们修改你的函数

function countryfind(){
    var fed;
    var selected = jQuery('#country_select option:selected').val();
    if(federations[selected] !== undefined) fed = federations[selected];
    else fed = {"name":"Default Name", "url":""}; //placeholders if it's not defined
    jQuery('#countrykey').text(
         selected + ' - ' + fed.name + ' ' + fed.url;
)};
Run Code Online (Sandbox Code Playgroud)

我不知道您希望它如何显示(为了简单起见,我只是将其转储为文本),但这将为您提供所需的数据,以便您可以从那里获取它