简体   繁体   中英

Radio buttons in foreach loop

i have a series of questions pulled from a database and need to loop radio buttons for each question. I need all of the answers returned to an array that looks something like this

$answer_grp1 = array("T", "T", "T");

My code looks like this. What is the correct (name=??) syntax to get an array into $_POST['answer_grp1']

<?php foreach ($questions as $question):
            if ($question['q_type']==1): ?>
                <tr>
                    <td style="width:5%;"><?= $question['q_number'] ?></td>
                    <td style="width:15%;">
                        T<input type="radio" name=answer_grp1[] value="T" />
                        F<input type="radio" name=answer_grp1[] value="F" />
                    </td>
                    <td><?= $question['q_text'] ?></td>
                </tr>
            <?php endif;
            endforeach; ?>

I would be inclined to use a for loop instead:

<?php 
  for ($i = 0; $i < count($questions); $i++) {
    $question = $questions[$i];
    if ($question['q_type']==1): ?>
      <tr>
              <td style="width:5%;"><?= $question['q_number']; ?></td>
              <td style="width:15%;">
                T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
                F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
               </td>
               <td><?= $question['q_text']; ?></td>
            </tr>
<?php endif;
        endfor; ?>

This is with your code:

<?php 
$i = 0;
foreach ($questions as $question):
        if ($question['q_type']==1): ?>
            <tr>
                <td style="width:5%;"><?= $question['q_number']; ?></td>
                <td style="width:15%;">
                    T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
                    F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
                </td>
                <td><?= $question['q_text']; ?></td>
            </tr>
        <?php endif; ?>
<?php 
$i++
endforeach; ?>

You would use

$_POST['answer_grp1'][0]
$_POST['answer_grp1'][1]

... and so on.

If all the answers were going to be in this one array, you could also loop through it like this:

for ($x=0; $x<count($_POST['answer_grp1']); $x++)
{
   $value = $_POST['answer_grp1'][$x];
}

As long as all the fields fall within one <form> tag and you submit the form, then the array should be available in the $_POST global.

Your naming for each input, answer_grp1[] is correct; however you should add quotes around the name.

You should also be adding semi-colons after your question output - change this:

<?= $question['q_text'] ?>

To this:

<?= $question['q_text']; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM