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; }
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; }
$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); } }
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; } }
<?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.
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 */ } }
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>"; }