PHP-用foreach删除重复项? [英] PHP - Remove duplicates with foreach?

查看:243
本文介绍了PHP-用foreach删除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组页码:

foreach($elements as $el) {
$pageno = $el->getAttribute("pageno");

echo  $pageno ;
}

可悲的是,它包含重复项.我尝试了以下代码,但不会返回任何内容:

Sadly it contains duplicates. I tried the follow code but it won't return a thing:

foreach(array_unique($elements) as $el) {
$pageno = $el->getAttribute("pageno");

echo  $pageno ;
}

如何删除重复的页码?在此先感谢:)

How to remove the duplicate page numbers? Thanks in advance :)

推荐答案

由于我没有您的数据结构,因此我提供了一个通用解决方案.如果我们知道$elements的结构,则可以对其进行优化,但是以下内容对您有用.

Since I do not have your data structure, I am providing a generic solution. This can be optimized if we know the structure of $elements but the below should work for you.

$pageNos = array();
foreach($elements as $el) {
   $pageno = $el->getAttribute("pageno");
   if(!in_array($pageno, $pageNos))
   {
       echo $pageno ;
       array_push($pageNos,$pageno);
   }
}

基本上,我们只是使用一个附加数组来存储打印的值.每次看到新值时,我们都会将其打印并添加到数组中.

Basically we are just using an additional array to store the printed values. Each time we see a new value, we print it and add it to the array.

这篇关于PHP-用foreach删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆