1

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;
    }
}
1
  • yes this is possible but what is specifically your problem? Commented Jul 3, 2012 at 19:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I figured it would be less code if I used a 2D array then use a switch, may just do that though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.