2014-03-19 234 views
1

如何使用for循环在数组中声明变量。我在页面上有3个输入字段,所以当按下提交按钮时,它应该处理下面的代码行。在我的html页面上,有一些字段命名为:question1,question2和question3。通过for循环声明php变量

以下是process.php文件的代码。由于某种原因它不起作用,我想这里有几个错误,但我找不到它们。

<?php 

$question = array(); 
for($j=1; $j<4; $j++) { 
    $question[j] = $_POST['question[j]']; 

$result; 
$n=1; 

if($question[j] != "") { 
    $result = $n.'): '.$question[j].'<br/><br/>'; 
    $n++; 
} 
} 

echo $result; 

?> 
+5

变量名应该以'$'为前缀。你的文字'j'将被解释为常量。无论何时不起作用,启用'error_reporting'。 – mario

+0

对于访问输入字段列表,建议在HTML表单中使用数组名称语法:'' – mario

回答

1

对于初学者来说,阵列零指数的,所以我想你想的:

for($j=0; $j<3; j++) 

除了形成,这不评价j值:

$_POST['question[j]'] 

我想你可能想要这样的东西:

$_POST["question$j"] 

然而,如果您做了上述索引变化,因为你的元素被命名为开始的1而不是0,那么你需要考虑的是:

$_POST['question' . $j+1] 
2
<?php 

$question = array(); 
$result = ""; 

for($j=1; $j<4; j++) { 
    $question[$j] = $_POST["question$j"]; 

    if($question[$j] != "") { 
     $result .= $j.'): '.htmlentities($question[$j]).'<br/><br/>'; 
    } 
} 

echo $result; 

?> 

尽管你不需要一个数组。

<?php 
$result = ""; 

for($j=1; $j<4; j++) { 
    $result .= $_POST["question$j"]!="" ? htmlentities($_POST["question$j"]).'<br/><br/>':'';   
} 

echo $result; 
?> 
0

您可以使用下面的HTML代码

<input type="text" name="question[a]" /> 
<input type="text" name="question[b]" /> 
<input type="text" name="question[c]" /> 

与下面的PHP代码:

foreach($_POST["question"] as $key => $value) 
{ 
    // $key == "a", "b" or "c" 
    // $value == field values 
} 

记住要净化你的输入!