我們?cè)?php 中有一個(gè)列表(數(shù)組),其設(shè)置如下$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這不起作用,看起來(lái)鍵在兩個(gè)示例中都被合并,而不是添加到末尾。我認(rèn)為這是因?yàn)?php 不存儲(chǔ)數(shù)組 as('A', 'B')而是 as (0=>'A',1=>'B'),并且我要合并的兩個(gè)數(shù)組都有 keys 0 and 1。所以我決定foreach ($children_ids as $child_id) { array_push($update_product_ids, (int)$child_id);}這感覺(jué)有點(diǎn)傻,因?yàn)楸仨氂幸环N方法可以一次性正確完成此操作?問(wèn)題:如何一次性合并上述數(shù)組?
1 回答

泛舟湖上清波郎朗
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以通過(guò) 實(shí)現(xiàn)您想要的目標(biāo)array_merge
。與 不同的是array_push
,array_merge
不會(huì)修改提供的數(shù)組。它而是返回一個(gè)新數(shù)組,該數(shù)組是所提供數(shù)組的串聯(lián)。所以基本上,做類(lèi)似的事情:
$update_product_ids = array_merge($update_product_ids, $child_ids);
如果您使用 PHP 5.6(或更高版本),您還可以使用“參數(shù)解包”:
array_push($update_product_ids, ...$child_ids);
如果您使用 PHP 7.4(或更高版本),則可以使用“擴(kuò)展運(yùn)算符”(與參數(shù)解包相同,但適用于數(shù)組):
$update_product_ids = [...$update_product_ids, ...$child_ids];
- 1 回答
- 0 關(guān)注
- 107 瀏覽