Ray
Ray

Reputation: 2728

form array of array checkboxes

I want to make an array that contains several arrays that store results of checkboxes.

category->subcategory->choice

I'm not sure if this is even possible but I want something like this maybe:

<input type="hidden" name="category[]" />
<input type="checkbox" name="subcat1[]" value="something" />
<input type="checkbox" name="subcat1[]" value="somewhere" />
<input type="checkbox" name="subcat2[]" value="something" />
<input type="checkbox" name="subcat2[]" value="somewhere" />

I want to be able to take the category array loop through it with PHP like this:

foreach($_POST['category'] as $sub){
    switch($sub){
        case 'subcat1':
            foreach($sub as $val){
                //prepare $val to insert into database X
            }
            break;
        case 'subcat2':
            foreach($sub as $val){
                //prepare $val to insert into database Y
            }
            break;
    }
}

Upvotes: 1

Views: 1017

Answers (1)

Jon
Jon

Reputation: 437376

It's even easier than you think:

<input type="checkbox" name="category[subcat1][]" value="something" />
<input type="checkbox" name="category[subcat1][]" value="somewhere" />
<input type="checkbox" name="category[subcat2][]" value="something" />
<input type="checkbox" name="category[subcat2][]" value="somewhere" />

And then:

foreach($_POST['category'] as $subCategoryName) {
    foreach ($subCategoryName as $item) {
        // ...
    }
}

If your intended treatment for different subcategories is not similar though, it would be better if you just posted them to different arrays.

Upvotes: 1

Related Questions