2012-11-20 76 views
61

嗨我試圖合併兩個數組,也想從最終數組中刪除重複值。PHP - 將兩個數組合併成一個數組(也是刪除重複)

這是我的陣列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 

) 

我想刪除這些重複的條目,或者我可以合併之前刪除這些... 普萊斯幫助.. 謝謝!!!!!!!

+0

因爲你想合併$ array1 [0]和$ array2 [0]而不是$ array1和$ array2。嘗試在每個陣列的第一項上運行array_merge – Bgi

+0

數組是動態的..所以它不會總是$ array1 [0]和$ array2 [0] – Ravi

+0

有什麼我可以比較數組內的每個對象的ID? ?? – Ravi

回答

3

嘗試使用array_unique()

這elminates複製您的陣列的列表中的數據..

4

將合併×2個陣列,並刪除重複

<?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

3

如前所述,可以使用array_unique(),但只能在處理簡單數據時使用。對象不是很容易處理。

當php嘗試合併數組時,它會嘗試比較數組成員的值。如果一個成員是一個對象,它不能得到它的值,而是使用spl散列。 Read more about spl_object_hash here.

簡單地告訴你是否有兩個對象,即同一類的實例,如果其中一個不是對另一個的引用 - 那麼最終會得到兩個對象,不管它們的屬性的值如何。

爲了確保您在合併數組中沒有任何重複,Imho您應該自行處理。

另外,如果您打算合併多維數組,請考慮使用array_merge_recursive()而不是array_merge()

相關問題