简体   繁体   English

如何使用foreach比较两个数组中的数据?

[英]How Can you compare the data from two arrays using foreach?

i have these two feeds(feed1,feed2), they both provide some ID'S, I'm trying to find out by looping through both of them if i can match ID'S, and if their is a match don't display that ID. 我有这两个供稿(feed1,feed2),它们都提供了一些ID,我试图通过遍历这两个供稿找出是否可以匹配ID,如果匹配则不显示该ID。

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

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

this is my code in PHP for displaying all of the ID's from two foreach loops, but i wanted them to be nested into each other, so if ID's in feed1 and feed2 match don't echo. 这是我的PHP代码,用于显示来自两个foreach循环的所有ID,但是我希望它们彼此嵌套,因此,如果feed1和feed2中的ID匹配,则不要回显。 so i presume their might be an if statement their somewhere. 所以我认为他们可能是一个if陈述他们的地方。 Thanks 谢谢

$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;
     }
}

First nested loop will echo item id from first feed which is not present in second and second foreach will echo id from second feed which is not present in first feed 第一个嵌套循环将回显第二个提要中没有的第一个提要中的项目ID,第二个foreach将回显第一个提要中不存在的第二个提要中的id

You could store the ID's of the one array of objects as a simple 1d array, and then whilst looping through the other feed, just check if the ID exists in the other. 您可以将一个对象数组的ID存储为一个简单的1d数组,然后在循环另一个提要时,只需检查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;
    }
}

Hope that helps. 希望能有所帮助。

If I understand the question right something like this should work. 如果我理解正确的问题,类似的东西应该可以工作。 You might be better to do it in an array as mentioned in other questions but this should work as well. 如在其他问题中提到的那样,您最好以数组的形式进行操作,但这也应该起作用。

$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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM