Reputation: 346
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;
}
Upvotes: 0
Views: 2553
Reputation: 945
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 */
}
}
Upvotes: 0
Reputation: 2597
<?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.
Upvotes: 0
Reputation: 714
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>";
}
Upvotes: -1
Reputation: 1548
$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);
}
}
Upvotes: 3
Reputation: 480
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;
}
}
Upvotes: 0