0

I have a foreach loop and have a problem with it. My loop show duplicate some item and I want show item only once and don't duplicate item. My loop it is.

 foreach($result as $res){ $id = $res->id; $title = $res->title; echo $title; } 
2
  • can you show the SELECT query for thisCommentedFeb 24, 2014 at 10:05
  • did you try anything for that?if yes ,please show your code and contents in $result
    – Shijin TR
    CommentedFeb 24, 2014 at 10:05

5 Answers 5

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

    try this one..

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

      another solution is, if you are getting this data from database then use DISTINCT in your select query.

        0

        Do a fast check & make your code execute faster like this:

        $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 */ } } 
          -1

          Try this:

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

            Start asking to get answers

            Find the answer to your question by asking.

            Ask question

            Explore related questions

            See similar questions with these tags.