Good day! Tell me, can anyone know how to check for matches in an associative array and replace the found matches with the word "Today" or "Yesterday" with php. The bottom line is that I make a news page, and it’s necessary that instead of a date there are necessary words.

<?php function get_news(){ $query = "SELECT news_id, title, anons, IF( DATE_FORMAT(NOW(), '%Y-%m-%d') = DATE_FORMAT(date, '%Y-%m-%d'), DATE_FORMAT(date, 'Сегодня'), IF( DATE_FORMAT(NOW(), '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(date, INTERVAL 1 DAY), '%Y-%m-%d'), DATE_FORMAT(date, 'Вчера'), DATE_FORMAT(date,'%d.%m.%y'))) as date_news, DATE_FORMAT(date,'%H:%i') as time_news, img FROM news ORDER BY news_id DESC LIMIT 4"; $res = mysql_query($query) or die(mysql_query()); $date = date("dmY"); $news = array(); while($row = mysql_fetch_assoc($res)){ $news[] = $row; } return $news; } ?> 

This problem was solved using MSQL, but I think that PHP is more suitable for this, and the code was just cumbersome.

 <?php function get_news(){ $query = "SELECT news_id, title, anons, DATE_FORMAT(date,'%d.%m.%y') as date_news, DATE_FORMAT(date,'%H:%i') as time_news, img FROM news ORDER BY news_id DESC LIMIT 4"; $res = mysql_query($query) or die(mysql_query()); $date = date("dmY"); $news = array(); while($row = mysql_fetch_assoc($res)){ $news[] = $row; // здесь как то надо заменить необходимые даты.. } return $news; } ?> 

Help me please!

  • And why do you need to climb on the array in addition. when you read $ row in your loop here and analyze and change. Same all in one field occurs $ row ['date'] == ... - Mike
  • 2
    And the meaning is implemented in sql well, it will be much easier then just to change the request and the date will be the date, the implementation in php will smell slightly. - Naumov
  • one
    Is it possible to write if ($ row ['date_news'] == date ("Ymd")) such a problem that such a question should be asked on CO? - Ipatiev

1 answer 1

You can do the following:

 <?php function get_news(){ $query = "SELECT news_id, title, anons, DATE_FORMAT(date,'%d.%m.%y') AS date_news, DATE_FORMAT(date,'%H:%i') AS time_news, img FROM news ORDER BY news_id DESC LIMIT 4"; $res = mysql_query($query) or die(mysql_query()); $today = date("dmY"); $yesterday = date("dmY", time() - 86400); $news = array(); while($row = mysql_fetch_assoc($res)){ if($row['date_news'] == $today) $row['date_news'] = 'Сегодня'; if($row['date_news'] == $yesterday) $row['date_news'] = 'Вчера'; $news[] = $row; } return $news; }