无法在 PHP 中连接 2 个数组 [英] Can't concatenate 2 arrays in PHP
问题描述
我最近学习了如何在 PHP 中使用 + 运算符连接 2 个数组.
I've recently learned how to join 2 arrays using the + operator in PHP.
但是考虑一下这段代码...
But consider this code...
$array = array('Item 1');
$array += array('Item 2');
var_dump($array);
输出是
array(1) { [0]=> string(6) "项目1" }
array(1) { [0]=> string(6) "Item 1" }
为什么这不起作用?跳过速记并使用 $array = $array + array('Item 2')
也不起作用.跟钥匙有关系吗?
Why does this not work? Skipping the shorthand and using $array = $array + array('Item 2')
does not work either. Does it have something to do with the keys?
推荐答案
两者都有一个 0
键,这种组合数组的方法将折叠重复项.尝试使用 array_merge()
代替.
Both will have a key of 0
, and that method of combining the arrays will collapse duplicates. Try using array_merge()
instead.
$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')
// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);
如果数组中的元素使用不同的键,+
运算符会更合适.
If the elements in your array used different keys, the +
operator would be more appropriate.
$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');
// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;
添加了一个代码片段来澄清
Added a code snippet to clarify
这篇关于无法在 PHP 中连接 2 个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!