user3246727
user3246727

Reputation: 111

php foreach loop items in equal dates

I have a php foreach loop my code is:

<?php 
  foreach($items as $item){
     
    echo $item->date;
    echo $item->title;
   }
?>

my out put for example this is:

2014-08-23

title1

2014-08-23

title2

2014-08-30

title3

but i want echo my item this format:

2014-08-23

title1

title2

2014-08-30

title3

i want echo Equal dates once and show items. how can do it? thank you

Upvotes: 1

Views: 321

Answers (2)

Bipon Biswas
Bipon Biswas

Reputation: 11635

You can try this

$temp = array();
foreach($items as $item){
    if (!in_array($item->date, $temp)){
        $temp[$item->title] = $item->date;
    }
}

foreach($temp as $title=>$date){       
    echo $date.'</br>';
    echo $title.'</br>';
}

Upvotes: 6

Barmar
Barmar

Reputation: 780781

$last_date = null;
foreach($items as $item){
    if ($item->date != $last_date) {
        echo $item->date;
        $last_date = $item->date;
    }
    echo $item->title;
}

Upvotes: 3

Related Questions