2014-02-24 255 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在你的選擇查詢中。