2014-02-24 211 views
0

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

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

你可以显示这个 –

+0

的SELECT查询吗?如果是,请在$ result中显示你的代码和内容 – Shin

回答

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); 
} 
} 
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; 
    } 
} 
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>"; 
} 
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在你的选择查询中。