2012-02-16 103 views
0

我有這兩個提要(feed1,feed2),他們都提供了一些ID,我試圖找出通過循環他們兩個,如果我可以匹配ID'S,如果他們是匹配不顯示該ID 。如何使用foreach比較兩個數組的數據?

foreach($feed->data as $item){ 
echo $item->id; 
} 

foreach($feed2->data as $item){ 
echo $item->id; 
} 

這是我在PHP代碼爲顯示所有ID的兩個foreach循環,但我希望他們可以相互嵌套,因此如果ID在FEED1和feed2比賽沒有迴音。所以我認爲他們可能是一個if語句他們的地方。由於

+0

注意它們提供了相同的數據,唯一的區別是我不打算在顯示中使用的一個屬性!如果你明白我的意思!! – MidnightCoder 2012-02-16 05:23:51

回答

2
$foundflag=false; 
foreach($feed->data as $item){ 
    foreach($feed2->data as $item1){ 
     if($item->id == $item1->id){ 
      $foundflag = true; 
      $array[]=$item1->id; 
     } 
    } 
    if(!$foundflag){ 
     echo $item->id; 
    } 
} 
foreach($feed2->data as $item1){ 
    if(!(in_array($item1->id,$array))){ 
     echo $item1->id; 
    } 
} 

首先嵌套循環會響應來自第一信息源項目ID是不存在於第二和第二的foreach迴音必從第二進料ID是不存在的第一進

0

你可以存儲的ID的將一個對象數組作爲一個簡單的1d數組,然後在循環其他feed時檢查另一個ID是否存在。

# Create your variables to store the ID's of the two feeds 
$ids_1 = array(); 
$ids_2 = array(); 

# Populate the arrays 
foreach ($feed->data as $item1) { 
    $ids_1[] = $item1->id; 
} 
foreach ($feed2->data as $item2) { 
    $ids_2[] = $item2->id; 
} 

# Loop through the first feed, and exclude the items that are the same in the second 
foreach($feed->data as $item){ 
    if (!in_array($item->id, $ids2)) { 
     echo $item->id; 
    } 
} 

# Loop through the second feed, and exclude the items that are the same in the first 
foreach($feed2->data as $item){ 
    if (!in_array($item->id, $ids1)) { 
     echo $item->id; 
    } 
} 

希望有所幫助。

0

如果我明白了這個問題,就應該這樣。正如其他問題中提到的那樣,您可能會更好地在數組中執行此操作,但這也應該起作用。

$items; 
foreach($feed->data as $item){ 
    echo $item->id; 
    foreach($feed2->data as $item2){ 
    echo $item2->id; 
    $pos = strrpos($items, $item2->id); 
    if ($item2->id != $item->id) && ($pos == false) 
     $items = $item2->id + ", "; 
    } 
} 

echo $items;