简体   繁体   中英

get a previous array value

I am making a php chat system and I would like to add a header for each day.

In order to achieve this I need a way to get both the current message date and the previous messgage date from my database, so I can use them in an if statement:

<?php if ($dtdate != $dtdateprev) : ?>

I am having a problem getting the previous entry date.

In order to get these values I use the following:

<?php
$sql=mysql_query("SELECT * FROM test");
while($row=mysql_fetch_array($sql)) {
    $dtval=$row['dtdate'];
    $dtvalprev= **???**;
    $dtdate=date_format(new DateTime($dtval), "D d M Y");
    $dtdateprev=date_format(new DateTime($dtvalprev), "D d M Y");
?>
<?php if ($dtdate != $dtdateprev) : ?>
<div>Example Header</div>
<?php endif; ?>
<div>Example Message Body</div>
<?php } ?>

So I need some help for $dtvalprev! Thanks in advance.

Try this,

<?php
$sql=mysql_query("SELECT * FROM test");
$dtvalprev= '';//previous value initially blank
while($row=mysql_fetch_array($sql)) {
    $dtval=$row['dtdate'];

    $dtdate=date_format(new DateTime($dtval), "D d M Y");
    if($dtdateprev)// check previous value should not blank
        $dtdateprev=date_format(new DateTime($dtvalprev), "D d M Y");

    ?>
    <?php if ($dtdate != $dtdateprev) : ?>
        <div>Example Header</div>
    <?php endif; ?>
    <div>Example Message Body</div>
    <?php 
    $dtdateprev=$dtval;// re-assign the current value
}
?>

You can get the previous date using a query:

select t.*,
       (select dtdate
        from test t2
        where t2.dtdate < t.dtdate
        order by dtdate desc
        limit 1
       ) as prevdtdate
from test t;

Alternatively, you can query the database in date order:

select t.*
from test t
order by dtdate;

And use logic in php to remember the previous value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM