如何将新的键值对推送到数组 php?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10810398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:06:13  来源:igfitidea点击:

How do i push a new key value pair to an array php?

phparraysdrupaldrupal-7drupal-modules

提问by Tallboy

I know there is a lot of documentation around this but this one line of code took me ages to find in a 4000 line file, and I would like to get it right the first try.

我知道有很多关于此的文档,但是这一行代码花了我很长时间才在一个 4000 行的文件中找到,我想在第一次尝试时就做对。

file_put_contents($myFile,serialize(array($email_number,$email_address))) or die("can't open file");
    if ($address != "[email protected]") {
        $email['headers'] = array('CC' => '[email protected]');
    }
}

After this if statement I basically want to add on

在此 if 语句之后,我基本上想添加

'BCC' => '[email protected]'

'BCC' => '[email protected]'

into the $email['headers']array (so it adds it whether the if evaluates to true or not)

$email['headers']数组中(因此无论 if 的计算结果是否为真,它都会添加它)

回答by Sampson

You can add them individually like this:

您可以像这样单独添加它们:

$array["key"] = "value";

Collectively, like this:

总的来说,像这样:

$array = array(
    "key"  => "value",
    "key2" => "value2"
);

Or you could merge two or more arrays with array_merge:

或者您可以合并两个或多个数组array_merge

$array = array( "Foo" => "Bar", "Fiz" => "Buz" );

$new = array_merge( $array, array( "Stack" => "Overflow" ) );

print_r( $new );

Which results in the news key/value pairs being added in with the old:

这导致新闻键/值对与旧的一起添加:

Array
(
  [Foo] => Bar
  [Fiz] => Buz
  [Stack] => Overflow
)

回答by KillerX

You can do this: $email['headers']['BCC'] = "[email protected]"but you need to add it after the if.

您可以这样做:$email['headers']['BCC'] = "[email protected]"但是您需要在 if 之后添加它。

回答by flowfree

$email['headers'] = array();

if ($address != "[email protected]") {
   $email['headers']['CC'] = '[email protected]';
}

$email['headers']['BCC'] = '[email protected]';