Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP连接数组(列表)并忽略重复键,因为我们只使用值_Php_Arrays - Fatal编程技术网

PHP连接数组(列表)并忽略重复键,因为我们只使用值

PHP连接数组(列表)并忽略重复键,因为我们只使用值,php,arrays,Php,Arrays,我们在php中有一个列表(数组),设置如下 $update_product_ids = array(); array_push($update_product_ids, (int)$product->getId()); // (int)$product->getId() is an integer The I tried: array_push($update_product_ids, array_values($child_ids)); // child_ids is an ar

我们在php中有一个列表(数组),设置如下

$update_product_ids = array();
array_push($update_product_ids, (int)$product->getId()); // (int)$product->getId() is an integer

The I tried:
array_push($update_product_ids, array_values($child_ids)); // child_ids is an array of integers
and
array_merge($update_product_ids, $child_ids); // child_ids is an array of integers
这不起作用,而且两个示例中的键似乎正在合并,而不是添加到末尾。我认为这是因为php不将数组存储为
('A','B')
,而是存储为
(0=>'A',1=>'B')
,我正在合并的两个数组都有键
0和1

所以我决定

foreach ($children_ids as $child_id) {
    array_push($update_product_ids, (int)$child_id);
}
这感觉有点傻,因为一定有一种方法可以在一次行动中纠正这一点


问题:如何一次性合并上述阵列?

您可以使用
array\u merge
实现所需。与
array\u push
不同,
array\u merge
不修改提供的数组。而是返回一个新数组,该数组是所提供数组的串联。所以基本上,做一些类似的事情:

$update_product_ids = array_merge($update_product_ids, $child_ids);

如果您使用的是PHP 5.6(或更高版本),还可以使用“参数解包”:


如果您使用的是PHP7.4(或更高版本),则可以使用“扩展运算符”(与参数解包相同,但适用于数组):


您是否尝试了
array\u unique(array\u merge($update\u product\u ids,$child\u ids))
array\u merge
工作正常。而
('A','B')
(0=>'A',1=>'B')
相同。你得到了什么样的结果?上面的任何一个都会做与否完全相同的事情吗?不会的。您正在比较两个数组,而在上面的答案中,我们正在“连接”两个数组。您好。抱歉,不是。您的问题是关于如何在您解释的特定情况下合并阵列。这就是上面的答案所要做的。你试过答案了吗?它起作用了吗?
array_push($update_product_ids, ...$child_ids);
$update_product_ids = [...$update_product_ids, ...$child_ids];