drr47973 2014-06-17 16:06
浏览 20
已采纳

循环生成多个选择 - 如何使用php记住每个选定选项上的发布数据

I have this loop which generates selects:

$loops=7;    
//for($j=1;$j<=$loops;$j++){
foreach($_SESSION['product'] as $key=>$val){    
$quantity = 7;    
$selqty = '<div class="optchk"><select name="qty[]" class="qty">';    
for($i=1;$i<=$quantity;$i++){    
$selqty.='<option value="'.$i.'">'.$i.'</option>';    

}
$selqty.='</select></div>';
}
echo '<form method="post" action="" name="orderform">';    
echo $selqty;
echo '<input type="submit" name="order_submit" value="Send"></form>';

How to keep each selected option for all those 7 selects after form submit? Thank you

post looks like :

array(7) { 
[0]=> string(1) "2" 
[1]=> string(1) "3" 
[2]=> string(1) "4" 
[3]=> string(1) "4" 
[4]=> string(1) "2" 
[5]=> string(1) "3" 
[6]=> string(1) "4"
}

and I tried the following :

<?php if($_POST['qty'] =$i) $selected= 'selected=selected';
$selqty.='<option '.$selected.' value="'.$i.'">'.$i.'</option>';
?>    

but it is wrong

  • 写回答

2条回答 默认 最新

  • dongzhao4036 2014-06-17 16:37
    关注

    As you are using action = "" you can check the values of qty[] and select the corresponding value for each select. Here is a working code:

    $loops=7; 
    $selqty = "";
    $j = 0;
    foreach($_SESSION['product'] as $key=>$val)
    {    
        $j++;
    $quantity = 7;    
    $selqty .= '<div class="optchk"><select name="qty[]" class="qty">';    
    for($i=1;$i<=$quantity;$i++)
    {    
        $selected = "";
        if(isset($_POST['qty']) && $i == $_POST['qty'][$j-1])
            $selected = "selected";
    
        $selqty.='<option value="'.$i.'"'.$selected.'>'.$i.'</option>';    
    }
    $selqty.='</select></div>';
    }
    echo '<form method="post" action="" name="orderform">';    
    echo $selqty;
    echo '<input type="submit" name="order_submit" value="Send"></form>';
    

    I also recommend you to get used to using double quotes when inserting php variables into strings:

    You can use

    $selqty.="<option value='$i' $selected> $i </option>";
    

    insetad of

    $selqty.='<option value="'.$i.'"'.$selected.'>'.$i.'</option>';
    

    Which I think is easier to read and understand.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输