Comparing dates of an array in PHP

Asked

Viewed 733 times

0

I’m trying to compare the dates that come from a database array to be able to organize them within a timeline. The problem is that I can’t compare the dates to know where to place each entry...

Maybe the problem is that within the array the dates are in date format, but if so, how to compare?

Follows the code:

<tbody>
    <tr>
        <td><center>Manhã</center></td>
                <?php 
                    foreach($periodo as $data){
                        while ($arrayBancas = mysql_fetch_array($oBanca->retorno())){
                            if ($arrayBancas['data'] == $data->format("Y-m-d")){
                                echo '<td>teste</td>';
                            }
                        }
                    }
                ?> 
     </tr>

Content of variables:

(Period)

if(!isset($_SESSION)) {session_start();} 

$idSemestre = $_SESSION['SemestreGeral'];

$oSemestre = new semestresclass();
$oSemestre -> listarEdicao($idSemestre);  

$array = mysql_fetch_array($oSemestre->retorno());

$start_date = $array['DataDeInicio'];
$end_date = $array['DataDeTermino'];

$inicio = new DateTime($start_date);
$fim = new DateTime($end_date);
$fim->modify('+1 day');

$interval = new DateInterval('P1D');
$periodo = new DatePeriod($inicio, $interval ,$fim);

(Array of Benches)

if(!isset($_SESSION)) {session_start();}  

$idSemestre = $_SESSION['SemestreGeral'];

$oBanca = new bancasclass();
$oBanca -> listar ($idSemestre);   

$arrayBancas = mysql_fetch_array($oBanca->retorno())

Follows the var_export value of the variables:

arrayBancas: array ( 0 => '1', 'idB' => '1', 1 => NULL, 'data' => NULL, 2 => NULL, 'time' => NULL, 3 => '316', 'room' => '316', )

date: Datetime::__set_state(array( 'date' => '2014-06-10 00:00:00', 'timezone_type' => 3, 'Timezone' => 'GMT', ))

  • You need to organize them as?

  • For days and shifts. In this case, inside this $arrayBancas there I have 'entries of a schedule' with time, date and place... then I’ll probably have to compare the time of each entry with which turn it fits and then play on the screen...

  • Try to better organize your query for data to come in a format that facilitates logic

  • Look if it helps you http://answall.com/questions/39631/howto compare a-frase-insertedwith as-existentes-na-bd-devolvendo-a-probabilid/39639#39639

  • No, it wasn’t that... I needed to compare date with string... How could I do?

  • In the database the date is stored as string? Or this as date?

  • In the bank she’s like Date

  • it’s strange that this if ($arrayBancas['data'] == strtotime('2014-06-05')){ echo '<td>teste</td>';} also doesn’t work...

  • Post the contents of $period and $arrayBancas using var_export().

  • I added the codes of each of them there in the question to be better understood

  • 2

    This doesn’t help because having the variables without having what they represent makes it impossible for any test to be done. By code we can even do a mental reverse engineering and we know that $array has two indices called Datadeinicio and Datadetermino. But so what? If, for example, we need to know the size of the arrays to figure out a solution we would not have as it may be only these two as can be more. I repeat, do a var_export() of the variables $array and $arrayBancas and edit the question again.

  • Now I understand! I did not know this function, very good! I put the values there, by q da to see the date is null, this may be preventing comparison right?

  • But the strange thing is that if I go through the array giving an echo in the array at the date position it prints the dates right... And now?

  • 1

    Great. I imagine this $arrayBancas should not return this much of null value, so you need to fix your query so that it returns workable data. In the meantime, you should also do a var_dump() to see if $array, $beginning, $end and $period and see if the objects are being filled with what is expected. Fixed this you can use the answer I will leave below.

Show 9 more comments

1 answer

1


With the recent issues you have two problems:

  1. Your query is not returning what is expected
  2. You’re comparing strings hoping to get notions of time

The first problem only you can solve because it would run too far from the topic’s scope (but that doesn’t stop you from creating another one if you have difficulties).

The second problem is very simple to solve, but requires you to fix your structure in the database.

For output of $arrayBancas You appear to have a DATETIME field but don’t have the time. Either you fix the way you input the data, so the time comes or you change the field type.

Datetime objects are comparable to conventional operators (<, >, == and !=) so once fixed the previous problem, just create a Datetime object with the left operand and make the comparison:

if( DateTime::createFromFormat( 'Y-m-d', $arrayBancas['data'] ) -> format( 'Y-m-d' ) == $data -> format( 'Y-m-d' ) ) {
    echo '<td>teste</td>';
}

If you choose to fix the way you enter the data and start having the hours you change the format of Y-m-d for Y-m-d H:i:s.

Remembering that the method Datetme::createFromFormat() was introduced in PHP 5.3.

  • Okay, I gave a general review, those NULL were there because of some tests I did and I forgot to delete it anyway, now I regularized! I’ll replace the var_export in the question with the var_dump for you to take a look! I found it curious that everything appears as a string

  • I have now tried to transform these array values with strtotime but did not roll...

  • var_dump() was just a hint to help you with a possible debugging. I reversed the changes not only because var_dump() doesn’t help much when posted but because otherwise the text I wrote would be meaningless. Now that I’ve seen how you are, you can remove the column hour and change the field type date from DATE to DATETIME, uniting the two. And you will not use strtotime(), you will create a Datetime object from the format that the date/time is in the database, as eud isse in the answer.

  • Okay, I got it, I did it. Now instead of having a DATE field and a TIME I have only DATETIME. So far so good, the problem is that now that variable $date that I use to walk between the two periods is not keeping the time... Just the date... How could I change the $date to go through the hours too?

  • 1

    Dateperiod works with time periods. The period P1D set will produce a date range. You can even format it as hours, but it will not result in what is expected. If you want the interval of hours from one day to the next, the period should be PT1H. If you want an hour a day, P1DT1H. And so it goes. Maybe if you show what you expect to have as output it becomes easier to assemble the period.

  • 1

    I edited the answer to make it even more evident.

  • It rolled!! Finally!! I couldn’t do Datetime::createFromFormat, my PHP here is 5.5 but nothing happens to it, so I did the following: if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d')) { echo 'goes'; } and finally rolled!! Thanks old, thank you!!!!! Now I will try to continue, if I lock again I open a new question!! Thanks!!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.