不能连接在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.
但想一想code ...
But consider this code...
$array = array('Item 1');
$array += array('Item 2');
var_dump($array);
输出为
阵列(1){[0] =>串(6)项目
1}
array(1) { [0]=> string(6) "Item 1" }
为什么这个不工作?跳过速记和使用 $阵列= $阵列+阵列(项目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;
编辑:增加了一个code段澄清
Added a code snippet to clarify
这篇关于不能连接在PHP 2阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!