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

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

未能array_merge(),在循環前輸出相同

未能array_merge(),在循環前輸出相同

PHP
天涯盡頭無女友 2022-08-05 09:28:56
我看到了許多相關的問題,沒有人為我回答這個問題 - 如果這是由于我缺乏知識,我很抱歉......我有一個數組,其中每條記錄如下所示,具有1多個聯系人:$contacts[{internal_id}]=>  array(3) {    [0]=>    array(6) {      ["name"]=>      string(13) "matching name"      ["bphone"]=>      string(13) "(123)345-5678"      ["cphone"]=>      string(13) "(321)345-6857"      ["hphone"]=>      string(13) "(123)543-5790"      ["email"]=>      string(0) ""      ["email2"]=>      string(0) ""    }    [1]=>    array(6) {      ["name"]=>      string(13) "matching name"      ["bphone"]=>      string(13) "(123)345-5678"      ["cphone"]=>      string(0) ""      ["hphone"]=>      string(0) ""      ["email"]=>      string(20) "[email protected]"      ["email2"]=>      string(21) "[email protected]"    }    [2]=>    array(6) {      ["name"]=>      string(17) "not matching name"      ["bphone"]=>      string(13) "(123)987-6453"      ["cphone"]=>      string(13) "(321)789-3546"      ["hphone"]=>      string(0) ""      ["email"]=>      string(21) "[email protected]"      ["email2"]=>      string(22) "[email protected]"    }  }我想合并任何類似的名字,每條記錄,保留相關的聯系信息。試試這個:    $i = 1; //1 > 0 so no need to +1 each time it's used in this case    foreach($contacts as $contact){        if($contact['name'] == $contacts[$i]['name']){            $contact = array_merge($contact, $contacts[$i]);            unset($contacts[$i]);        }        $i++;    }我的預期/期望輸出將是:[{internal_id}]=>  array(2) {    [0]=>    array(6) {      ["name"]=>      string(13) "matching name"      ["bphone"]=>      string(13) "(123)345-5678"      ["cphone"]=>      string(13) "(321)345-6857"      ["hphone"]=>      string(13) "(123)543-5790"      ["email"]=>      string(20) "[email protected]"      ["email2"]=>      string(21) "[email protected]"    }但是這個循環沒有任何影響,至少不是我能找到的。我的實際輸出與初始數組匹配。我在這里錯過了什么?編輯/更新:通過引用/值傳遞的簡單混合。感謝@Barmar的快速解決方案。數組中沒有反映任何更改,因為我從未真正告訴php更新這些值。令人震驚的是它是如何工作的。
查看完整描述

1 回答

?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

您的代碼不起作用的原因有兩個:

  1. 賦值給 不會更改數組,它只是重新賦值變量。$contact

  2. array_merge()不就地修改數組,它將返回一個新數組。

您可以通過創建引用變量來解決這兩個問題。$contact

foreach ($contacts as &$contact) {
    ...
}


查看完整回答
反對 回復 2022-08-05
  • 1 回答
  • 0 關注
  • 87 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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