我們在 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_push
,array_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];
- 1 回答
- 0 關注
- 108 瀏覽
添加回答
舉報
0/150
提交
取消