如何从php数组创建一个html单选按钮列表?

时间:2014-04-23 12:08:44

标签: php html mysql

我有以下代码(它是一段更大的代码):

<?php
  include_once 'init/init.funcs.php';
  $x = $_SESSION['answering']['index'];
  echo $_SESSION['answering']['questions'][$x-1];
  $result4 = mysql_query('SELECT kysimus_id FROM katse_kysimused 
             where kysimus= "' .$_SESSION['answering']['questions'][$x] . '"');
  $question_id = mysql_result($result4, 0);
  $result5 = mysql_query('SELECT * from katse_valik_vastused 
                                   where kysimus_id="'. $question_id . '"');
  if($result5 === FALSE) {
    die(mysql_error());
  }
  while($row = mysql_fetch_assoc($result5)) {
    $options[] = $row['vasuts'];
  }
  //foreach($options as $option=>$option_value) {
  //echo $option_value;
  $count=count($options);
?>
<html>
  <br>
  <form method="post" action="answering.php">
    <input type="radio" name="1"><?php echo $options[0]?><br>
    <input type="radio" name="2"><?php echo $options[1]?><br>
    <input name= "submit" type="submit" value="Vasta">
  </form>
</html>

现在有两个固定的单选按钮。但我希望它拥有尽可能多的按钮,因为许多元素都在数组&#34;选项&#34;并且它们中的每一个都有一个写在其旁边的元素的值。我怎么能这样做?

5 个答案:

答案 0 :(得分:3)

为此使用for循环:http://www.php.net/manual/en/control-structures.for.php

for ($i = 1; $i < count($options); $i++) {
?>
<input type="radio" name="<?php echo $i; ?>"><?php echo $options[$i]?><br>
<?php
}

答案 1 :(得分:1)

试试这样:

<?php
  while($row = mysql_fetch_assoc($result5)) {
    $options[] = $row['vasuts'];
}
?>
<html>
<br>
<form method="post" action="answering.php">
<?php 
foreach($options as $option=>$option_value) {
    ?>
   <input type="radio" name="<?= $option; ?>"><?php echo $option_value?><br>

<?php }?>
<input name= "submit" type="submit" value="Vasta">
</form>

答案 2 :(得分:1)

<html>
<br>
<form method="post" action="answering.php">
<?php
    foreach ($options as $index=>$option) {
        echo "<input type='radio' name='{$index}'>{$option}<br>";
    }
?>
<input name= "submit" type="submit" value="Vasta">
</form>
</html>

答案 3 :(得分:0)

尝试使用以下代码。

<html>
    <br>
    <form method="post" action="answering.php">
        <?php
        foreach ($options as $key => $value) {
            ?>
            <input type="radio" name="<?php echo $key; ?>"><?php echo $options[$key] ?><br>
            <?php
        }
        ?>


        <input name= "submit" type="submit" value="Vasta">
    </form>
</html>

答案 4 :(得分:0)

你可以为每个人使用,例如:

<form method="post" action="answering.php">
    <?php foreach ($options as $key => $value): ?>
        <input type="radio" name="<?php echo $key; ?>" /><?php echo $value; ?><br />
    <?php endforeach; ?>
    <input name= "submit" type="submit" value="Vasta">
</form>