PHP Post Multi Checkbox Устанавливает массив - PullRequest
0 голосов
/ 18 марта 2020

У меня есть форма, которая включает в себя несколько наборов флажков, где имя входа динамически создается (name = "'. $ Name.' []"). Результат HTML выглядит примерно так:

<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>

Когда он отправлен, я знаю, что он выглядит как многомерный массив, но как я могу получить значение имени ввода с помощью оператора foreach? В настоящее время я пробовал это, но это не дает мне значение имени входа.

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

, который возвращает (если все проверено):

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

Мне нужно имя ввода в качестве идентификатора задачи:

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

Спасибо заранее за любую помощь в этом.

1 Ответ

2 голосов
/ 18 марта 2020

Ваш $ _POST будет содержать имена сообщений формы в качестве ключей. Итак, вам нужно будет получить ключ от вашего первого foreach l oop, как показано ниже:

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