循环生成多个选择 - 如何使用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

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.

You can reload the page after the submit with the parameters from the form data, just see if its selected in the data you got and generate the appropriate html for it