在foreach循环中回显PHP变量
问题描述:
我的主页设置如下。它有2个文本框和从文本文件填充的复选框列表(我没有使用数据库作为其简单的形式)。我的问题是,我不能在复选框博文的值和回声他们在foreach循环中回显PHP变量
<!DOCTYPE HTML>
<html>
<body>
<?php
$CN = $Assignee ="";
?>
<form action="GPParser1.php" method="post">
<table>
<tr>
<td>CName:</td>
<td><input type="text" name="CN"></td>
</tr>
<tr>
<td>Assignee:</td>
<td><input type="text" name="Assignee" ></td>
<tr>
<tr>
<td>Select Vendors:</td>
</tr>
<td>
<?php
$gp = file('GP.txt');
foreach ($gp as $line_num => $gp)
{
//echo '<input type="checkbox" name= $line value=$line>($line)."<br />\n";
print "
<br/>
<input type='checkbox' name='" . $gp . "' value='" . $gp . "'>$gp";
};
?>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit">
</td>
<?php
echo $CasinoName;
echo $Assignee;
//foreach ($gp as $ln => $gp) {
// echo $gp;
//};
?>
</body>
<html>
和:
<!DOCTYPE HTML>
<html>
<body>
<?php
$CN = $_POST["CN"];
$Assignee = $_POST["Assignee"];
$GPS = $_POST ["$gp"];
echo $CN;
echo $Assignee;
foreach ($GPS as $GPss => $GPS)
{
echo "$GPS";
}
//foreach ($gp as $ln => $gp) {
// echo $gp;
//};
?>
</body>
<html>
因为它是现在我周围$ GPS =根据得到的几个误区$ _ POST [ “$ GP”];
我该怎么办?
答
我不能肯定这是否是一种解决方案,你”重新寻找如果我错了,请让我知道,所以我可以给出更好的答案。
我的解决方案是,你的表单将有一个复选框列表,当表单被提交时,它将成为一个值的数组。
<!DOCTYPE HTML>
<html>
<body>
<?php
$CN = $Assignee ="";
?>
<form action="GPParser1.php" method="post">
<table>
<tr>
<td>CName:</td>
<td><input type="text" name="CN"></td>
</tr>
<tr>
<td>Assignee:</td>
<td><input type="text" name="Assignee"></td>
<tr>
<tr>
<td>Select Vendors:</td>
</tr>
<td>
<?php
$gp = file('GP.txt');
foreach ($gp as $line_num => $gp) { ?>
<p><input type="checkbox" name="gp[]" value="<?php echo $gp; ?>">
<?php echo $gp; ?>
</p>
<?php }; ?>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit">
</td>
</tr>
</body>
</html>
<!DOCTYPE HTML>
<html>
<body>
<?php
$CN = $_POST["CN"];
$Assignee = $_POST["Assignee"];
$GPS = $_POST["gp"];
echo $CN;
echo $Assignee;
foreach ($GPS as $GPss => $GPS)
{
echo "$GPS";
}
//foreach ($gp as $ln => $gp) {
// echo $gp;
//};
?>
</body>
<html>
+1
谢谢,这正是我需要的! –
答
在这两个脚本,你在foreach覆盖变量循环
foreach ($gp as $line_num => $gp)
// this ^^^
// ^^^ overwrites this
和
foreach ($GPS as $GPss => $GPS)
// this ^^^
// ^^^ overwrites this
,因为你正在使用的as
而是双方相同的变量名使用另一个像这样的varibale名称
foreach ($gp as $line_num => $gpx)
的一般做法是命名使用pluralised名称,如$items
和不用其他的singluar变量包含数组的数组变量,像
foreach ($gps as $line_num => $gp)
您$ GP变量需要声明只有当你使用它的环路键 - >值($ GP)是不是很好的实践,尽量限制重新命名为不同的名称。 – 2017-09-23 16:14:20
目前,你有复选框交替改变'name'值,这意味着没有办法PHP可以期望知道什么'名称'值进来,这可能是什么PHP抛出的错误。你希望它是这样吗?还是你想要向PHP发送一组值? –