PHP追加一个阵列到另一个(不array_push或+) [英] PHP append one array to another (not array_push or +)
本文介绍了PHP追加一个阵列到另一个(不array_push或+)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何追加一个阵列到另一个没有比较他们的钥匙?
$ a =阵列('A','B');
$ B =阵列('C','D');
在结束它应该是:阵列([0] =>在[1] => B [2] => C [3] => D)
如果我使用类似 []
或 array_push
,就会导致这些结果之一:
阵列([0] =>在[1] => B [2] =>数组([0] => C [1] = D 1和D ))
//要么
阵列([0] =&以及c [1] = D 1和D)
这只是应该是,这样做,但在一个更优雅的方式:
的foreach($ B $ AS VAR)
$ A [] = $ VAR;
解决方案
array_merge
是优雅的方式:
$ a =阵列('A','B');
$ B =阵列('C','D');
$合并= array_merge($ A,$ B);
// $合并现在等于阵列('一个','B','C','D');
做这样的事情:
$合并= $ A + $ B;
// $合并现在等于阵列(A,B)
就不行,因为 +
运营商实际上并没有合并。如果他们 $ A
具有相同的密钥 $ B
,它不会做任何事情。
How to append one array to another without comparing their keys?
$a = array( 'a', 'b' );
$b = array( 'c', 'd' );
At the end it should be: Array( [0]=>a [1]=>b [2]=>c [3]=>d )
If I use something like []
or array_push
, it will cause one of these results:
Array( [0]=>a [1]=>b [2]=>Array( [0]=>c [1]=>d ) )
//or
Array( [0]=>c [1]=>d )
It just should be something, doing this, but in a more elegant way:
foreach ( $b AS $var )
$a[] = $var;
解决方案
array_merge
is the elegant way:
$a = array('a', 'b');
$b = array('c', 'd');
$merge = array_merge($a, $b);
// $merge is now equals to array('a','b','c','d');
Doing something like:
$merge = $a + $b;
// $merge now equals array('a','b')
Will not work, because the +
operator does not actually merge them. If they $a
has the same keys as $b
, it won't do anything.
这篇关于PHP追加一个阵列到另一个(不array_push或+)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文