亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 108 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號