問題描述
嗨我正在嘗試合併兩個陣列也想從最終的陣列刪除重複的值。
這是我的陣列 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。