PHP合并两个数组

时间:2011-08-04 21:26:12

标签: php arrays

我正在尝试使用array_merge()合并两个数组,但是我收到以下警告:

警告:array_merge()[function.array-merge]:参数#1不是第41行的数组

以下是代码:

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

echo "<ul>";

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

echo "</ul>";
?>

<h4>Add more options (comma separated)</h4>
<form method="post" action="index2.php">
<input type="text" name="added" />
<?php
foreach ($travel as $t){
    echo "<input type=\"text\" name=\"travel[]\" value=\"$t\" />\n";
 }
 ?>
 <input type="submit" name="submit" value="Add" /> 
 </form>
 <?php
$travel = $_POST["travel"];
  $added = explode(",", $_POST["added"]);

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

print_r ($travel);


?>

3 个答案:

答案 0 :(得分:3)

您将$_POST["travel"](不是数组而是字符串)分配给$travel。首先把它变成一个数组。

答案 1 :(得分:1)

您正在访问$_POST["travel"],但如果您未提交表单,则无法定义。你需要检查它是否是一个帖子请求:

<?php
if(isset($_POST["travel"])){
    $travel = $_POST["travel"];
    $added = explode(",", $_POST["added"]);

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

print_r ($travel);
?>

答案 2 :(得分:0)

$_POST是一个数组$_POST['travel']但是它只是一个元素,除非它来自多选元素。