Do not replicate items if they exists in a foreach loop

My head is clearly not working here. The logic is simple but I can’t seem to get it right.

I have a tv schedule post type and I want to display:

2016-12-01
2017-04-01
2017-05-17

Instead of:

2016-12-01
2017-03-01
2017-03-01
2017-03-01
2017-03-01
2017-03-01

At the moment I am stuck with repeating times. I want to only show one time if it already exists as in the first case.

This is my code:


`<?php 
$args = array(
    'post_type' => 'tv-schedule',
    'posts_per_page' => -1,
    'orderby' => 'date',
    'order' => 'ASC',
    'post_status' => array('publish', 'future'),
);
$posts_array = query_posts($args); 

foreach ($posts_array as $post_array) {
    $date = $post_array->post_date_gmt;
    $new_date = date ('Y-m-01', strtotime($date) );
    echo $new_date . '<br />';

    /*
    if(!in_array($new_date, $post_array->post_date_gmt)){
        //$a[]=$value;
        echo "test";
    }
    */

}`

you’re just missing to add $post_array->post_date_gmt to $new_date if not in_array(). respect the signature: in_array($needle, $haystack)

If the dates are always in order, and you only want to show the new date when it changes from the previous date, you could just keep a record of the previous date

$lastdate = "";
foreach (...) {
  $newdate = whatever;
  if ($newdate != $lastdate) echo $newdate;
  $lastdate = $newdate;
}
1 Like

Thank you. Don’t think that is going to work. The new_date is only converted to make sense in the select fields only. Do I make sense?

on unordered lists just put $post_array->post_date_gmt into an array after you checked it with in_array()

@droopsnoot I love you man <3

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.