为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
哈士奇WWW 2023-09-22 15:01:26
我们在 php 中有一个列表(数组),其设置如下$update_product_ids = array();array_push($update_product_ids, (int)$product->getId()); // (int)$product->getId() is an integerThe I tried:array_push($update_product_ids, array_values($child_ids)); // child_ids is an array of integersandarray_merge($update_product_ids, $child_ids); // child_ids is an array of integers这不起作用,看起来键在两个示例中都被合并,而不是添加到末尾。我认为这是因为 php 不存储数组 as('A', 'B')而是 as (0=>'A',1=>'B'),并且我要合并的两个数组都有 keys 0 and 1。所以我决定foreach ($children_ids as $child_id) {    array_push($update_product_ids, (int)$child_id);}这感觉有点傻,因为必须有一种方法可以一次性正确完成此操作?问题:如何一次性合并上述数组?
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

您可以通过 实现您想要的目标array_merge。与 不同的是array_pusharray_merge不会修改提供的数组。它而是返回一个新数组,该数组是所提供数组的串联。所以基本上,做类似的事情:

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

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

array_push($update_product_ids, ...$child_ids);

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

$update_product_ids = [...$update_product_ids, ...$child_ids];


查看完整回答
反对 回复 2023-09-22
  • 1 回答
  • 0 关注
  • 50 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信