-2

我正在尝试获取表单数组中的复选框数组。我试图首先将数据作为表单数组获取,然后在数组中获取复选框数组。

<form name="preview" id="post" action="" method="post">
    <input type="hidden" name="category[$id]" />
    <input type="checkbox" name="subcat[]" value="something" />
    <input type="checkbox" name="subcat[]" value="somewhere" />
    <input type="checkbox" name="subcat[]" value="something" />
    <input type="checkbox" name="subcat[]" value="somewhere" />

    <input type="hidden" name="category[$id]" />
    <input type="checkbox" name="subcat[]" value="something" />
    <input type="checkbox" name="subcat[]" value="somewhere" />
    <input type="checkbox" name="subcat[]" value="something" />
    <input type="checkbox" name="subcat[]" value="somewhere" />
    <input class="button-primary" name="submit_preview" value="Submit Selected Tees" type="submit">
</form>
if (isset($_POST['submit_preview'])) {
    foreach ( $_POST[ 'category' ] as $id ) {
        foreach ( $_POST[ 'subcat' ][$id] as $subcat ) {
             echo $subcat;
        }
    }
}
4

1 回答 1

0

Mindreading:您获得所有类别的所有复选框值,但希望按类别进行。--> 您必须通过名称属性将子类别(复选框)链接到类别。

$categories:数组持有idname你的类别:

<form name="preview" id="post" action="" method="post">
<?
foreach ($categories as $cat) { // for each of your categories 4 checkboxes

    echo "<p>category: {$cat['name']}</p>";
    echo "<input type=\"checkbox\" name=\"cat_{$cat['id']}_sub[]\" value=\"something\" /> option 1<br />";
    echo "<input type=\"checkbox\" name=\"cat_{$cat['id']}_sub[]\" value=\"something\" /> option 2<br />";
    echo "<input type=\"checkbox\" name=\"cat_{$cat['id']}_sub[]\" value=\"something\" /> option 3<br />";
    echo "<input type=\"checkbox\" name=\"cat_{$cat['id']}_sub[]\" value=\"something\" /> option 4<br />";
    // name of checkbox if id=1: "cat_1_sub[]"

} // foreach

<input class="button-primary" name="submit_preview" value="Submit Selected Tees" type="submit">
</form>

提交后:

if (isset($_POST['submit_preview'])) {

    foreach ( $_POST as $name => $value) {

        if (substr($name,0,4)=='cat_') echo "$name: $value <br />";

    } // foreach
} // if isset
于 2013-03-03T01:04:43.327 回答