我有以下HTML:
<input type="checkbox" name="plusfri[]" value="Fri"> Friday
<input type="checkbox" name="plussat[]" value="Sat"> Saturday
<input type="checkbox" name="plussun[]" value="Sun"> Sunday
<input type="checkbox" name="plusmon[]" value="Mon"> Monday
发布到以下PHP:
$plus = array(array("Name" => "", "Days" => "", "Age" => "","Conc" => ""));
foreach($_POST['plusname'] as $k => $p)
{
$plus[$k]['Name'] = $p;
$plus[$k]['Age'] = $_POST['plusage'][$k];
$plus[$k]['Conc'] = $_POST['plusconc'][$k];
$plus[$k]['Days'] = "X";
if($_POST['plusfri'][$k]=="Fri") $plus[$k]['Days'] .= "1";
if($_POST['plussat'][$k]=="Sat") $plus[$k]['Days'] .= "2";
if($_POST['plussun'][$k]=="Sun") $plus[$k]['Days'] .= "3";
if($_POST['plusmon'][$k]=="Mon") $plus[$k]['Days'] .= "4";
}
我最终得到了:
array(3) {
[0]=>
array(4) {
["Name"]=>
string(6) "FRISAT"
["Days"]=>
string(3) "X12"
["Age"]=>
string(1) "1"
["Conc"]=>
string(0) ""
}
[1]=>
array(4) {
["Name"]=>
string(6) "SATSUn"
["Age"]=>
string(1) "1"
["Conc"]=>
string(0) ""
["Days"]=>
string(3) "X23"
}
[2]=>
array(4) {
["Name"]=>
string(6) "SUNMON"
["Age"]=>
string(1) "1"
["Conc"]=>
string(0) ""
["Days"]=>
string(3) "X34"
}
}
有谁能告诉我为什么'Days'只在元素[1]和[2]上跳到了最后?&gt;
答案 0 :(得分:1)
这是因为你的循环。要获得相同的键顺序,您应该以相同的顺序设置值,如下所示:
$plus = array(array("Name" => "", "Days" => "", "Age" => "","Conc" => ""));
foreach($_POST['plusname'] as $k => $p)
{
$plus[$k]['Name'] = $p;
$plus[$k]['Days'] = "X"; // <-- see ?
$plus[$k]['Age'] = $_POST['plusage'][$k];
$plus[$k]['Conc'] = $_POST['plusconc'][$k];
if($_POST['plusfri'][$k]=="Fri") $plus[$k]['Days'] .= "1";
if($_POST['plussat'][$k]=="Sat") $plus[$k]['Days'] .= "2";
if($_POST['plussun'][$k]=="Sun") $plus[$k]['Days'] .= "3";
if($_POST['plusmon'][$k]=="Mon") $plus[$k]['Days'] .= "4";
}
答案 1 :(得分:0)
因为您在循环外声明了$plus[0]
的顺序,所以当您运行第一个循环迭代时,您将替换$plus[0]
中变量的值赋值。在后续迭代中,因为您尚未预先声明$plus[1]
,$plus[2]
等,所以您将全新的变量分配给 empty 数组。
如果您想保留订购,请尝试此操作:
$plus = array();
foreach($_POST['plusname'] as $k => $p)
{
$plusChild = array("Name" => "", "Days" => "", "Age" => "","Conc" => "");
$plusChild['Name'] = $p;
$plusChild['Age'] = $_POST['plusage'][$k];
$plusChild['Conc'] = $_POST['plusconc'][$k];
$plusChild['Days'] = "X";
if($_POST['plusfri'][$k]=="Fri") $plusChild['Days'] .= "1";
if($_POST['plussat'][$k]=="Sat") $plusChild['Days'] .= "2";
if($_POST['plussun'][$k]=="Sun") $plusChild['Days'] .= "3";
if($_POST['plusmon'][$k]=="Mon") $plusChild['Days'] .= "4";
$plus[$k] = $plusChild;
}
或者,您可以替换它:
$plus = array(array("Name" => "", "Days" => "", "Age" => "","Conc" => ""));
有了这个:
$plus = array(array("Name" => "", "Days" => "", "Age" => "","Conc" => ""),array("Name" => "", "Days" => "", "Age" => "","Conc" => ""),array("Name" => "", "Days" => "", "Age" => "","Conc" => ""));
但只有当你知道你总会有三次回报时,这才有效。