将用户输入添加到数组

时间:2011-08-06 04:30:51

标签: php arrays array-merge

我正在尝试使用array_merge将用户输入添加到以前创建的数组中。但是,我无法将整个新数组作为无序列表回显。正在正确处理用户的条目,但原始数组在无序列表中显示为“数组”。这是代码:

<?php
$travel = array("Automobile", "Jet", "Ferry", "Subway");

foreach ($travel as $t)
    {
    echo "<ul>";

    echo "<li>$t</li>";

    echo "</ul>";

    }
?>

<form action="arrays.php" method="post">
<input type="text" name="added" />
<?php

foreach ($travel as $t)
{
echo "<input type=\"text\" name=\"travel[]\" value=\"$t\" />";      
}

?>
<input type="submit" name="submit" value="Add More!" />
</form>

<?php

$travel = array($_POST["travel"]);

$added = explode(",", $_POST["added"]);

$travel = array_merge($travel, $added);

echo "<p> Here is the list with your additions:</p>";

echo "<ul>";

foreach ($travel as $t)
{
echo "<li>$t</li>";
}

echo "</ul>";
?>

3 个答案:

答案 0 :(得分:0)

尝试为array_merge()创建的新数组使用新的变量名。我想你可能会遇到修改你存储的数组的问题。

答案 1 :(得分:0)

$travel = array($_POST["travel"]);

应该是

$travel = $_POST['travel'];

答案 2 :(得分:0)

问题解决了:

if (isset($_POST["submit"]))
{
$travel = $_POST["travel"];
$added = explode(",", $_POST["added"]);
$travel = array_merge($travel, $added);


echo "<p> Here is the list with your additions:</p>";

echo "<ul>";

foreach ($travel as $t)
    {
    echo "<li>$t</li>";
    }

echo "</ul>";
}
?>