如何修复PHP数组爆炸结果在“表单选择”中仅显示最后一个值?

时间:2019-03-24 07:31:51

标签: php pdo explode

PHP数组爆炸结果仅在表单选择中显示最后一个值,而打印功能显示所有值。 HTML部分应在下拉菜单中显示所有值。当前,它仅显示最后一个值。

MYSQL

Table Name: op_subject_combination
Id = 1 and its op_subject_combo_sub1 values are (chemistry, physics, mathematics)

PHP部件

<?php   

 $select_enquiry="SELECT * FROM op_subject_combination where id = '1' order by id desc limit 20";
 $sql=$dbconn->prepare($select_enquiry);
 $sql->execute();
 $wlvd=$sql->fetchAll(PDO::FETCH_OBJ);
 if($sql->rowCount() > 0){  
   foreach($wlvd as $rows){
      $str = $rows->op_subject_combo_sub1;
      $arr = explode( ",", $str ) ;
      foreach ($arr as $row1)
?>

HTML部分

<div class="form-group">
   <label for="exampleInputEmail1">Session Name</label>
   <select class="form-control" id="op_subject_combo_session" name="op_subject_combo_session" >
      <option selected><?php echo $rows4->st_center; ?></option>
      <option>--------</option>
      <option><?php  echo  $row1   ;?></option>
      <?php }} ?>
   </select>
</div>

2 个答案:

答案 0 :(得分:0)

您进行foreach,然后在循环完成后回显,因此仅输出最后一个值。您想要的是:

<?php
foreach ($arr as $row1)
{
   echo "<option>" .$row1 . "</option>";
}
?>
</select>

FWIW,我猜是因为您不了解在foreach声明后省略花括号而导致的情况。剧透警报:?>之前,foreach循环已完成,这可能有助于使它更加清晰:PHP - If/else, for, foreach, while - without curly braces?

答案 1 :(得分:0)

您的嵌套错误。 foreach应该仅包含<option>,如下所示。您还应该根据某些条件在单个选项上设置selected。并且value=""用于每个选项。 Kindof,拿一支笔和一支笔,用自然语言写下您要做什么以及输出结果。

<?php   
    $select_enquiry="SELECT * FROM op_subject_combination where id = '1' order by id desc limit 20";
    $sql=$dbconn->prepare($select_enquiry);
    $sql->execute();
    $wlvd=$sql->fetchAll(PDO::FETCH_OBJ);
    if($sql->rowCount() > 0){  
        foreach($wlvd as $rows){
?>
<div class="form-group">
   <label for="exampleInputEmail1">Session Name</label>
   <select class="form-control" id="op_subject_combo_session" name="op_subject_combo_session" >
<?php
            $str = $rows->op_subject_combo_sub1;
            $arr = explode( ",", $str ) ;
            foreach ($arr as $row1) {
?>
      <option <?=$row1==$rows4->st_center?' selected':''?>>
        <?php echo $row1; ?>
      </option>
<?php
            }
?>
      <option>--------</option>
   </select>
</div>
<?php 
        } 
    }
?>