简体   繁体   English

如何在php中将一个数组追加到另一个数组

[英]how to append an array to another arrays in php

I have to arrays in script 我必须在脚本中数组

    $users = array("A", "B", "C", "D", "E");
    $newUsers = array("F", "G", "H", "I");
    $totalUsers = $users + $newUsers;

By using Union operator, I tried to append $newUser array to $users . 通过使用Union运算符,我尝试将$ newUser数组追加到$ users

And store it in $totalUsers , after printing the $totalUsers by using print_r($totalUsers) . 并将其存储在$ totalUsers,使用的print_r($ totalUsers)打印$ totalUsers后。

It printed out only the $users array contents. 它只打印$ users数组的内容。 Why ? 为什么呢

I used the array_merge($users + $newUsers) and also it printed only the $users array contents. 我使用了array_merge($ users + $ newUsers) ,并且它只打印了$ users数组的内容。

Finally by using one of the following methods, 最后,通过使用以下方法之一,

method 1: 方法1:

    $totalUsers = array_merge(array_values($users), array_values($newUsers));
    print_r($totalUsers);

method 2: 方法2:

    array_merge($users, $newUsers);
    print_r($totalUsers);

I got the correct output 我得到正确的输出

(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => E
    [5] => F
    [6] => G
    [7] => H
    [8] => I
)

What was the problem, and what is different between the above methods?? 问题是什么,上述方法之间有什么区别?

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. 对于两个数组中都存在的键,将使用左侧数组中的元素,而右侧数组中的匹配元素将被忽略。

http://www.php.net//manual/en/language.operators.array.php http://www.php.net//manual/en/language.operators.array.php

In other words, it only adds elements from the right hand if the keys don't already exist in the left hand array. 换句话说,如果键在左手数组中不存在,则仅从右手添加元素。 That explains why it does nothing in your case. 这就解释了为什么您不执行任何操作。

array_merge($users + $newUsers)

This does exactly the same, an array union, and afterwards does an array_merge on the result. 这样做完全相同,是数组联合,然后对结果进行array_merge So it does nothing either. 因此,它也不执行任何操作。

array_merge($users, $newUsers)

This does exactly what you want, it's the correct thing to do. 这正是您想要的,这是正确的事情。

array_merge(array_values($users), array_values($newUsers))

This does the exact same thing as well, array_values does nothing in this case. 这也做同样的事情,在这种情况下, array_values不做任何事情。

$totalUsers = array_merge($users, $newUsers);

That is the correct way to use array_merge . 那是使用array_merge的正确方法。 You can also input more then two arrays to be merged. 您还可以输入两个以上要合并的数组。

EDIT: To read more on the array operators, please visit this link: http://php.net/manual/en/language.operators.array.php 编辑:要了解有关数组运算符的更多信息,请访问以下链接: http : //php.net/manual/en/language.operators.array.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM