我看到了許多相關的問題,沒有人為我回答這個問題 - 如果這是由于我缺乏知識,我很抱歉......我有一個數組,其中每條記錄如下所示,具有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個贊
您的代碼不起作用的原因有兩個:
賦值給 不會更改數組,它只是重新賦值變量。
$contact
array_merge()
不就地修改數組,它將返回一個新數組。
您可以通過創建引用變量來解決這兩個問題。$contact
foreach ($contacts as &$contact) { ... }
- 1 回答
- 0 關注
- 87 瀏覽
添加回答
舉報
0/150
提交
取消