Christian Mayne Christian Mayne - 17 days ago 5
PHP Question

Getting values from a PHP associative array using jQuery

I Have a html select element generated in PHP from an array as follows

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


The select box uses a small javascript function to displays the country key of the selected country:

function countryfind(){
jQuery('#countrykey').text(
jQuery('#country_select option:selected').val()
)};


I want to now use that key to interface with another PHP array which contain information about the country and display that country in the #countrykey div instead of the selected value:

$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'),
);


Is this something that can be easily achieved, or is my approach entirely wrong?

Answer

You're on the right track here. So, here's how to get this to do what you want

Within your <script> block we want to output that array in JSON

var federations = <?php echo json_encode($si_federations); ?>;

Now, when you run countryfind we want to pull the value out of that object and display it as well. So let's modify your function

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;
)};

I don't know how you want it displayed (I just dumped it as text for simplicity), but this gets you the data you need so you can take it from there