On 6/22/2011 3:43 PM, Adam Preece wrote:
> Hi Gang!
> 
> i have 2 assoc arrays from 2 querys, 
> 
> first one is page categorys it consists of:
>       id
>       name
> 
> second is pages
>       name
>       cat_id
> 
> now, i am using smarty, so i pass arrays into the view. this i would like to 
> pass to the view and display within a html select element.
> 
>       <select id="name">
>               <option value="CAT_ID">CAT NAME
>                       <option disabled="disabled">PAGE NAME ASSOCIATED TO THE 
> CAT NAME</option>
>               </option>
>       </select>
> 
> and i cannot think of how i can structure an array to pass in to achieve this 
> and/or is it even possible :-/.
> 
> i hope this makes sense.
> 
> i'm truly stuck!
> 
> kind regards
> 
> Adam Preece
>       

I see that you have a nested <option ...> tag.  Maybe you are looking for the
<optgroup> tag.

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

<?php

$categories[] = array('id' => 1, 'name' => 'cars');
$categories[] = array('id' => 2, 'name' => 'trucks');
$categories[] = array('id' => 3, 'name' => 'motorcycles');

$pages[] = array('id' => 1, 'name' => 'Neon', 'cat_id' => 1);
$pages[] = array('id' => 2, 'name' => 'Saturn', 'cat_id' => 1);
$pages[] = array('id' => 3, 'name' => 'F150', 'cat_id' => 2);
$pages[] = array('id' => 4, 'name' => 'Ram 2500', 'cat_id' => 2);
$pages[] = array('id' => 5, 'name' => 'Suzuki', 'cat_id' => 2);
$pages[] = array('id' => 6, 'name' => 'Honda', 'cat_id' => 3);

echo "<select id=\"page_id\">\n";

foreach ($categories AS $cat) {
  $c_cat_name = htmlspecialchars($cat['name']);
  echo "\t<optgroup label=\"{$c_cat_name}\">\n";

  foreach ($pages AS $page) {
    if ( $page['cat_id'] == $cat['id'] ) {
      $c_page_id = htmlspecialchars((int)$page['id']);
      $c_page_name = htmlspecialchars($page['name']);
      echo "\t\t<option value=\"{$c_page_id}\">{$c_page_name}</option>\n";
    }
  }
  # Reset pages so you can loop through it again
  reset($pages);
  echo "\t</optgroup>\n";
}

echo "</select>\n";
?>

All the above is untested, but should get you very close to what I think you are
trying to accomplish.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to