开发者

Add up content of array to another array in php

I want to have an array that contains a list of something, then I have another array that contains a list of something. I want to add those arrays up to each other.

For example, I have this

<?php
$greetings1 = array (
      'a' => 'hello',
      'b' => 'hi'
      );
$greetings2 = array ('c' => 'hey',
      'd' => 'greetings'
     );
array_push($greetings1, $greetings2);

foreach($greetings1 as $a => $b) {
 echo $a.' and '.$开发者_如何学Gob."<br/>";
}
?>

I want it so that the output is:

a and hello

b and hi

c and hey

d and greetings

the real output of the php code above is:

a and hello

b and hi

0 and Array

So how do I properly add the two arrays up?

Thanks!


You can array_merge

<?php
$greetings1 = array(
    'a' => 'hello',
    'b' => 'hi',
);
$greetings2 = array(
    'c' => 'hey',
    'd' => 'greetings',
);

$greetings = array_merge($greetings1, $greetings2);

Which will output:

Array
(
    [a] => hello
    [b] => hi
    [c] => hey
    [d] => greetings
)


array_merge($greetings1, $greetings2);

array_push just adds an element at the end of the array (in that case another array).


You're looking for array_merge

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜