php foreach循环显示重复项目

时间:2014-02-24 10:02:15

标签: php foreach

我有一个foreach循环并且遇到问题。我的循环显示重复一些项目,我只想显示项目一次,不要重复项目。我的循环是。

  foreach($result as $res){
     $id    = $res->id;
     $title = $res->title;
     echo $title;
   }

5 个答案:

答案 0 :(得分:3)

$partial=array();
foreach($result as $res){
if (!in_array($res->id, $partial)) {
   $id = $res->id;
   $title = $res->title;

   echo $title;
   array_push($partial, $res->id);
}
}

答案 1 :(得分:0)

尝试这个..

$present_array = array();

foreach($result as $res){
   if(!in_array($res->title, $present_array)){
     $present_array[] = $res->title;
     $id    = $res->id;
     $title = $res->title;
     echo $title;
   }
}

答案 2 :(得分:0)

试试这个:

$result = array(
                array(
                    'id'        => "1",
                    'title'     => "My title"
                    ),
                array(
                    'id'        => "2",
                    'title'     => "My title 2"
                    )
                );

foreach($result as $res){
   $id = $res['id'];
   $title = $res['title'];
   echo $title . "<br>";
}

答案 3 :(得分:0)

<?php 
function remove_dup($matriz) { 
    $aux_ini=array(); 
    $entrega=array(); 
    for($n=0;$n<count($matriz);$n++) 
    { 
        $aux_ini[]=serialize($matriz[$n]); 
    } 
    $mat=array_unique($aux_ini); 
    for($n=0;$n<count($matriz);$n++) 
    { 

            $entrega[]=unserialize($mat[$n]); 

    } 
    return $entrega; 
} 

foreach(remove_dup($result) as $res){
     $id    = $res->id;
     $title = $res->title;
     echo $title;
}

另一种解决方案是,如果您从数据库获取此数据,请在选择查询中使用DISTINCT

答案 4 :(得分:0)

进行快速检查,使代码执行得更快,如下所示:

$check_dup = array();
foreach ($items as $item){
    if (in_array($item['id'], $check_dup))
        continue;
    else {
        array_push($check_dup, $item['sid']);

        /* your code in foreach loop */
    }
}