問題描述
嗨我正在嘗試合併兩個數組也想從最終的數組刪除重複的值。
這是我的陣列 1:
Array
(
[0] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
)
這是我的陣列 2:
Array
(
[0] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
)
我使用 array_merge 將這兩個數組合併成一個數組。它是這樣輸出
Array
(
[0] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
[1] => stdClass Object
(
[ID] => 749
[post_author] => 1
[post_date] => 2012-11-20 06:26:07
[post_date_gmt] => 2012-11-20 06:26:07
)
我想刪除這個重複的條目,或者我可以在合併之前刪除它… 請求幫助.. 謝謝!!!!!!!
最佳解決方案
array_unique(array_merge($array1,$array2), SORT_REGULAR);
http://se2.php.net/manual/en/function.array-unique.php
次佳解決方案
如上所述,可以使用 array_unique(),但只能在處理簡單數據時使用。對象不是那麼簡單的處理。
當 php 嘗試合併數組時,它會嘗試比較數組成員的值。如果一個成員是一個對象,它將無法獲取其值並使用 spl 哈希。 Read more about spl_object_hash here.
簡單的説,如果你有兩個對象,同一個類的實例,如果其中一個不是對另一個的引用 – 你最終會有兩個對象,無論其屬性的價值。
為了確保你在合併的數組中沒有任何重複的內容,Imho 你應該自己處理這種情況。
另外,如果要合併多維數組,請考慮在 array_merge()上使用 array_merge_recursive()。
第三種解決方案
嘗試使用 array_unique()
這樣可以清除數組列表中的重複數據。
第四種方案
它會合並兩個數組並刪除重複
<?php
$first = 'your first array';
$second = 'your second array';
$result = array_merge($first,$second);
print_r($result);
$result1= array_unique($result);
print_r($result1);
?>
嘗試這個鏈接 link1
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。