mercredi 18 mars 2020

PHP Post Multi Checkbox Sets Array

I have a form that includes multiple checkbox sets, where the name of the input is dynamically created (name="'. $name .'[]"). The HTML result looks something like this:

<tr>
<td><input type="checkbox" name="1[]" value="Jan"/></td>
<td><input type="checkbox" name="1[]" value="Feb"/></td>
</tr>
<tr>
<td><input type="checkbox" name="2[]" value="Jul"/></td>
<td><input type="checkbox" name="2[]" value="Sep"/></td>
<td><input type="checkbox" name="2[]" value="Dec"/></td>
</tr>
<tr>
<td><input type="checkbox" name="3[]" value="May"/></td>
<td><input type="checkbox" name="3[]" value="Aug"/></td>
</tr>

When its submitted, I know it comes across as a multi-dimensional array but how can I get the value of the input's name using a foreach statement? Currently I have tried this but it does not give me the value of the input's name.

foreach ($_POST as $task){
    foreach ($task as $key => $month){
        echo '<p>Task ID is: '. $task .' and the month check is '. $month .'';
    }       
}

Which returns (if all is checked):

Task ID is: Array and the month check is Jan
Task ID is: Array and the month check is Feb
Task ID is: Array and the month check is Jul
Task ID is: Array and the month check is Sep
Task ID is: Array and the month check is Dec
Task ID is: Array and the month check is May
Task ID is: Array and the month check is Aug

I need the input name as the Task ID:

Task ID is: 1 and the month check is Jan
Task ID is: 1 and the month check is Feb
Task ID is: 2 and the month check is Jul
Task ID is: 2 and the month check is Sep
Task ID is: 2 and the month check is Dec
Task ID is: 3 and the month check is May
Task ID is: 3 and the month check is Aug

Thank you in advanced for any help with this.




Aucun commentaire:

Enregistrer un commentaire