使用foreach使用数组填充其他变量


Using an array to populate other variables using a foreach

简单地说,我有一个表单,它有三个相同的输入字段。名称不同;然而,当发布时,它们具有相同的结构,只是名称前缀不同(即三个系统具有不同的名称前缀:它们将是windowstitle、mactitle、linuxtitle等)。

目前,我有一个流程,只适用于一个同名的窗口标题(当然,如果填写了表格)

代码看起来像这样:

<?php
$title = $_POST['windowstitle'];
//validate info or redirect
if ($title != "" ) {
    $title = mysql_real_escape_string($title);
    $sql = "insert into newwindows (title) values ('$title');
    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
?>

此外,表单块看起来像这个

<form action="newuserprocess.php" method="post" enctype="multipart/form-data">
<div class="form">
    <h3>Windows</h3>
    <!-- title of system name -->
    <p><label for="windowstitle"> edition of system </lable></p>
    <input type="text" name="windowstitle"  size=20 /><br />
    </div>
    <div class="form">
    <h3>Mac</h3>
    <!-- title of system name -->
    <p><label for="mactitle"> edition of system </lable></p>
    <input type="text" name="mactitle"  size=20 /><br />
    </div>
<p><input type="submit" id="submit" class="bigbutton" value="Upload" /></p>
</form>

然而,这就忽略了其他表单,唯一的区别是我想要输入的db和post-value前缀不同。

所以我想出了一个我认为很聪明的解决方案:

<?php
$arr = array('windows', 'mac', 'linux');
foreach ($arr as &$value) {
    $title = $_POST['$valuetitle'];
    //validate info 
    if ($title != "" ) {
        $title = mysql_real_escape_string($title);
        $sql = "insert into new$value (title) values ('$title');
        $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
    }
?>

然而,这是行不通的。我知道部分原因;因为''使变量显示为原样,所以我的$_Post将始终返回为$value。另一个原因与我的新$value数据库名称相同。这个的正确格式是什么?我该如何做到这一点?

您可能想要

$title = $_POST[$value . 'title'];

$sql = "insert into new$value (title) values ('$title')";

Another reason is the same with my new$value database name. My question is what is the proper format for this?

为了清晰起见,我将把$value放在括号{$value}中。您的格式有效,但可能更清晰。请参阅一些测试:http://ideone.com/A2kWU

此外,如果您不更改数组$arr中的值,那么您应该只使用

foreach ($arr as $value) { //...

以防止意外更改。不过,在这种情况下,这并不是什么大不了的事,因为您只使用了一次数组。

编辑您的代码,如:

<?php
     $arr = array('windows', 'mac', 'linux');
     foreach ($arr as $value) {