使用“+”合并两个数组(数组联合运算符)它是如何工作的?

发布于 2024-08-19 01:56:49 字数 319 浏览 12 评论 0原文

我有一些代码似乎使用 += 合并两个数组中的数据,但它不包含元素中的所有元素。它是如何运作的?

示例:

$test = array('hi');
$test += array('test', 'oh');
var_dump($test);

输出:

array(2) {
  [0]=>
  string(2) "hi"
  [1]=>
  string(2) "oh"
}

在 PHP 中的数组上使用 + 意味着什么?

I have some code that appears to merge the data from two arrays using +=, but it doesn't include all of the elements in the element. How does it work?

Example:

$test = array('hi');
$test += array('test', 'oh');
var_dump($test);

Output:

array(2) {
  [0]=>
  string(2) "hi"
  [1]=>
  string(2) "oh"
}

What does + mean when used on arrays in PHP?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

人疚 2024-08-26 01:56:49

引自 PHP 语言运算符手册

+ 运算符返回附加到左侧数组的右侧数组;对于两个数组中都存在的键,将使用左侧数组中的元素,而右侧数组中的匹配元素将被忽略。

因此,如果您这样做,

$array1 = ['one',   'two',          'foo' => 'bar'];
$array2 = ['three', 'four', 'five', 'foo' => 'baz']; 

print_r($array1 + $array2);

您将得到

Array
(
    [0] => one   // preserved from $array1 (left-hand array)
    [1] => two   // preserved from $array1 (left-hand array)
    [foo] => bar // preserved from $array1 (left-hand array)
    [2] => five  // added from $array2 (right-hand array)
)

所以 + 的逻辑相当于以下代码片段:

$union = $array1;

foreach ($array2 as $key => $value) {
    if (false === array_key_exists($key, $union)) {
        $union[$key] = $value;
    }
}

如果您对 C 级实现的详细信息感兴趣,请前往


注意,+array_merge() 的方式不同组合数组:

print_r(array_merge($array1, $array2));

会给你

Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [foo] => baz // overwritten from $array2
    [2] => three // appended from $array2
    [3] => four  // appended from $array2
    [4] => five  // appended from $array2
)

查看链接页面以获取更多示例。

Quoting from the PHP Manual on Language Operators

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

So if you do

$array1 = ['one',   'two',          'foo' => 'bar'];
$array2 = ['three', 'four', 'five', 'foo' => 'baz']; 

print_r($array1 + $array2);

You will get

Array
(
    [0] => one   // preserved from $array1 (left-hand array)
    [1] => two   // preserved from $array1 (left-hand array)
    [foo] => bar // preserved from $array1 (left-hand array)
    [2] => five  // added from $array2 (right-hand array)
)

So the logic of + is equivalent to the following snippet:

$union = $array1;

foreach ($array2 as $key => $value) {
    if (false === array_key_exists($key, $union)) {
        $union[$key] = $value;
    }
}

If you are interested in the details of the C-level implementation head to


Note, that + is different from how array_merge() would combine the arrays:

print_r(array_merge($array1, $array2));

would give you

Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [foo] => baz // overwritten from $array2
    [2] => three // appended from $array2
    [3] => four  // appended from $array2
    [4] => five  // appended from $array2
)

See linked pages for more examples.

爱要勇敢去追 2024-08-26 01:56:49

我发现使用它的最好例子是在配置数组中。

$user_vars = array("username"=>"John Doe");
$default_vars = array("username"=>"Unknown", "email"=>"[email protected]");

$config = $user_vars + $default_vars;

正如它所暗示的,$default_vars 是默认值的数组。
$user_vars 数组将覆盖 $default_vars 中定义的值。
$user_vars 中的任何缺失值现在都是 $default_vars 中的默认变量。

这将 print_r 为:

Array(2){
    "username" => "John Doe",
    "email" => "[email protected]"
}

我希望这有帮助!

The best example I found for using this is in a config array.

$user_vars = array("username"=>"John Doe");
$default_vars = array("username"=>"Unknown", "email"=>"[email protected]");

$config = $user_vars + $default_vars;

The $default_vars, as it suggests, is the array for default values.
The $user_vars array will overwrite the values defined in $default_vars.
Any missing values in $user_vars are now the defaults vars from $default_vars.

This would print_r as:

Array(2){
    "username" => "John Doe",
    "email" => "[email protected]"
}

I hope this helps!

一桥轻雨一伞开 2024-08-26 01:56:49

该运算符采用两个数组的并集(与 array_merge 相同,但使用 array_merge 会覆盖重复键)。

数组运算符的文档位于此处

This operator takes the union of two arrays (same as array_merge, except that with array_merge duplicate keys are overwritten).

The documentation for array operators is found here.

陌路终见情 2024-08-26 01:56:49

如果应该保留数字键或者您不想丢失任何联合合并的内容,请小心使用

$a = array(2 => "a2", 4 => "a4", 5 => "a5");
$b = array(1 => "b1", 3 => "b3", 4 => "b4");

数字

print_r($a+$b);
Array
(
    [2] => a2
    [4] => a4
    [5] => a5
    [1] => b1
    [3] => b3
)

print_r(array_merge($a, $b));
Array
(
    [0] => a2
    [1] => a4
    [2] => a5
    [3] => b1
    [4] => b3
    [5] => b4
)

Carefull with numeric keys, if they should be preserved or if you don't want to loose anything

$a = array(2 => "a2", 4 => "a4", 5 => "a5");
$b = array(1 => "b1", 3 => "b3", 4 => "b4");

union

print_r($a+$b);
Array
(
    [2] => a2
    [4] => a4
    [5] => a5
    [1] => b1
    [3] => b3
)

merge

print_r(array_merge($a, $b));
Array
(
    [0] => a2
    [1] => a4
    [2] => a5
    [3] => b1
    [4] => b3
    [5] => b4
)
箹锭⒈辈孓 2024-08-26 01:56:49

+ 运算符产生与 array_replace()< 相同的结果/a>.但是,由于运算符参数是相反的,因此结果数组的顺序也可能不同。

扩展本页的另一个示例:

$array1 = array('one', 'two', 'foo' => 'bar');
$array2 = array('three', 'four', 'five', 'foo' => 'baz'); 

print_r($array1 + $array2);
print_r(array_replace($array2, $array1)); //note reversed argument order

输出:

Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [foo] => bar // preserved from $array1
    [2] => five  // added from $array2
)
Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [2] => five  // added from $array2
    [foo] => bar // preserved from $array1
)

The + operator produces the same results as array_replace(). However since the operator arguments are reversed, the ordering of the resulting array may also be different.

Expanding on another example from this page:

$array1 = array('one', 'two', 'foo' => 'bar');
$array2 = array('three', 'four', 'five', 'foo' => 'baz'); 

print_r($array1 + $array2);
print_r(array_replace($array2, $array1)); //note reversed argument order

outputs:

Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [foo] => bar // preserved from $array1
    [2] => five  // added from $array2
)
Array
(
    [0] => one   // preserved from $array1
    [1] => two   // preserved from $array1
    [2] => five  // added from $array2
    [foo] => bar // preserved from $array1
)
迷鸟归林 2024-08-26 01:56:49

来自 https://softonsofa.com/php-array_merge- vs-array_replace-vs-plus-aka-union/

话虽这么说,我们可以认为 + 运算符有点多余,因为使用 array_replace 函数也可以实现同样的效果。

但是,在某些情况下它会派上用场:假设您有一个 $options 数组传递给函数/方法,并且还有默认值用作后备:

// we could do it like this
function foo(array $options)
{
   $defaults = ['foo' => 'bar'];
   
   $options = array_replace($defaults, $options);
 
   // ...
}
 
// but + here might be way better:
function foo(array $options)
{
   $options += ['foo' => 'bar'];
 
   // ...
}

From https://softonsofa.com/php-array_merge-vs-array_replace-vs-plus-aka-union/

That being said, we could think of the + operator as kinda redundant, since the same can be achieved with array_replace function.

However, there are cases, where it comes in handy: say you have an $options array being passed to a function/method, and there are also defaults to be used as fallback:

// we could do it like this
function foo(array $options)
{
   $defaults = ['foo' => 'bar'];
   
   $options = array_replace($defaults, $options);
 
   // ...
}
 
// but + here might be way better:
function foo(array $options)
{
   $options += ['foo' => 'bar'];
 
   // ...
}
滴情不沾 2024-08-26 01:56:49
  1. 数组加运算将所有数组视为关联数组。
  2. 加号时按键冲突时,保留左(前一个)值

我发布下面的代码以使事情变得清楚。

$a + $b = array_plus($a, $b)

function array_plus($a, $b){
    $results = array();
    foreach($a as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
    foreach($b as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
    return $results;
}
  1. Array plus operation treats all array as assoc array.
  2. When key conflict during plus, left(previous) value will be kept

I post the code below to make things clear.

$a + $b = array_plus($a, $b)

function array_plus($a, $b){
    $results = array();
    foreach($a as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
    foreach($b as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
    return $results;
}
或十年 2024-08-26 01:56:49

它将把新数组追加到前一个数组中。

It will append the new array to the previous.

北音执念 2024-08-26 01:56:49
$var1 = "example";
$var2 = "test";
$output = array_merge((array)$var1,(array)$var2);
print_r($output);

数组([0] => 示例 [1] => 测试)

$var1 = "example";
$var2 = "test";
$output = array_merge((array)$var1,(array)$var2);
print_r($output);

Array ( [0] => example [1] => test )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文