PHP array_replace 仅检查 $_POST 中的元素

PHP array_replace only checked elements from $_POST

如何仅替换 从 post 提交的数组元素

我有一个带有多个复选框的表单,我将所有复选框提交到一个 PHP 页面,我想在该页面中替换另一个数组。

形式:

$oldArray = array(
  "colors" => array(1 => "mandarin", "strawberry", "blueberry", "kiwi", "banana"),
  "other"  => array(1 => "test1", "test2", "test3", "test4")
);

目标页面:

$newArray = array(
  "colors" => array(1 => "orange", "red", "blue", "green", "yellow"),
  "other"  => array(1 => "example1", "example2", "example3", "example4")
);

print_r( array_replace($_POST['colors'], $newArray['colors']) );

如果我只检查两个元素,"mandarin" 和 "kiwi",array_replace returns:

Array (
  [1] => orange <--- OK
  [2] => strawberry 
  [3] => blueberry 
  [4] => green  <--- OK 
  [5] => banana
)

如何才能echo只有$_POST个元素?

例如

 Array (
  [1] => orange
  [4] => green 
)

尝试:

 print_r(array_intersect ($_POST['colors'],$newArray['colors']));

你应该post数组键通过。试试这个:

$oldArray = array(
    "colors" => array(1 => "mandarin", "strawberry", "blueberry", "kiwi", "banana"),
    "other"  => array(1 => "test1", "test2", "test3", "test4")
);

echo '<select name="colors">';
foreach ($oldArray['colors'] as $key => $val)
{
    echo '<option value="'.$key.'">'.$val.'</option>';
}
echo '</select>';

然后在您收到的 PHP 页面中,您可以执行以下操作:

$newArray = array(
    "colors" => array(1 => "orange", "red", "blue", "green", "yellow"),
    "other"  => array(1 => "example1", "example2", "example3", "example4")
);

foreach($_POST['colors'] as $key)
{
    echo $newArray['colors'][$key];
}