将新值推送到数组,同时保持旧值不变


Push new values to array while keeping old one intact

不知道如何解释这一点或寻找这方面的答案。

我正在创建一个要发送的表单,希望使用现有数组并将其推送到新数组,而不影响旧数组。

这就是我现在正在做的:

$required_fields = array( "full_name", "email", "phone", "preferred_date" );
$whitelist = array_push( $required_fields, "patient_type", "appointment_time", "comments");

但是,当以这种方式执行时,它会更改$required字段数组。如何在不影响$required_fields的情况下将这些现有值推送到$whitelist数组中?

我想你可能想要array_merge:

$whitelist = array_merge( $required_fields, array(
  "patient_type", 
  "appointment_time", 
  "comments"
));

这将使$required_fields单独存在,而$whitelist将是:

array(
  "full_name", 
  "email", 
  "phone", 
  "preferred_date", 
  "patient_type", 
  "appointment_time", 
  "comments"
);

http://php.net/manual/en/function.array-push.php

如果你看一下array_push的文档,它实际上修改了第一个参数,只返回数组中新元素的数量。

您要做的是复制required_fields数组,然后添加一些新元素。您可以使用array_merge函数来完成此操作。

http://www.php.net/manual/en/function.array-merge.php

您可能需要使用array_merge。请注意,array_merge只接受类型为array的参数。

相反,当您使用array_push时,第一个参数本身就会被修改。如果您查看array_push的文档,第一个参数是通过引用传递的,并且会被自己修改,这就是为什么在您的案例中$required_fields会被修改。

因此,正确的代码应该是:

$required_fields = array( "full_name", "email", "phone", "preferred_date" );
$whitelist = array_merge( $required_fields, array("patient_type", "appointment_time",  "comments"));