Search code examples
phpajaxarraysloopsfill

Loop through multidimensional array from AJAX with jquery to populate select


A multidimensional returned from php, here is my php array:

$brands = array("Bmw" => "200" ,"Mercedes" => "201", "Audi" => "202");

When the data is returnend how can I populate a select with this info?

Lets assume that I need fill a select with Brands and their ID.

<select>
  <option value="200">Bmw</option>
  <option value="201">Mercedes</option>
  <option value="202">Audi</option>
</select>

I dont know how to loop through the returned array to fill the select.

Thanks a lot!!


Solution

  • Use it this way.

    $brands = array("Bmw" => "200" ,"Mercedes" => "201", "Audi" => "202");
    $output = "<select>";
    foreach($brands as $keys => $val){
        $output .= '<option value="'.$val.'">'.$keys.'</option>';
    }
    $output .= "</select>";
    echo $output;