Kupigon
Kupigon

Reputation: 307

Making select option with two options?

I have a main-categories and sub-categories:

Category: applications
Subcategory: windows
Category: applications
Subcategory: linux
Category: movies
Subcategory: xvid

Here's my <select>:

<select name="category">
    <optgroup label="APPLICATIONS">
        <option value="applications[windows]">Windows</option>
        <option value="applications[Linux]">Linux</option>
    </optgroup>
    <optgroup label="MOVIES">
        <option value="movies[xvid]">Xvid</option>
    </optgroup>
</select>

Is there a good way for PHP to recognize which is the main-category and sub-category after the form submit?

The other way I think about is: applications_windows and then explode the underscore.

Upvotes: 2

Views: 112

Answers (1)

mend3
mend3

Reputation: 516

$data = array(
    'applications' => array(
        'windows', 'linux'
    ),
    'movies' => array(
        'xvid'
    )
);

$select = '<select name="category">';
foreach($data as $catName => $catData){
    $select .= '<optgroup label="'.$catName.'">';
    foreach($catData as $item){
        $select .= '<option value="'.$catName.'['.$item.']">'.$item.'</option>';
    }
    $select .= '</optgroup>';
}
$select .= '</select>';

echo $select;

This will return this:

This will return this.

Upvotes: 1

Related Questions