在 foreach 循环中跳过相同的日期

skip same dates in foreach loop

这是聊天数据库的文本文件内容

you:2016-05-02 11:41:53 Hi

Muhammad:2016-05-02 11:42:41 Hi

you:2016-05-02 11:43:33 How are you ?

Muhammad:2016-05-02 14:44:56 I'm fine!

这是循环获取内容的代码

<?php
$chat = file("members/cdn/1/chats/9188.txt");
foreach($chat as $line){
    $name = strchr($line,":",true);
    $message = explode(' ', substr(strchr($line,":"),1), 3);
    if(some thing){
    ?>
    <div>
      <!-- here i want to skip the same dates -->
      <?=$message[0];?>
    </div>
    <?php
    }
    ?>
    <div class="container">
      <div class="arrow">
        <div class="outer"></div>
        <div class="inner"></div>
      </div>
      <div class="message-body">
        <p><?=$message[2];?></p>
        <p class="message_time"><?=date("g:i a", strtotime($message[1]));?></p>
      </div>
    </div>
    <div class="spacer"></div>
    <?php
}
?>

我希望消息的日期在同一日期的消息之上出现一次

试试这个:

$prevDate[] = array();
foreach($chat as $line){
    $name = strchr($line,":",true);
    $message = explode(' ', substr(strchr($line,":"),1), 3);
    if(some thing){
    ?>
    <div>
      <!-- here i want to skip the same dates -->
      <?php 
        if(!in_array($message[0],$prevDate)) { // check if date exist in array - means displayed previously or not
          echo $message[0]; 
          $prevDate = $message[0]; // store date in array so that next time you can check whether it has been already displayed or not
        }
      ?>
    </div>
    <?php
    }
    ?>
    <div class="container">
      <div class="arrow">
        <div class="outer"></div>
        <div class="inner"></div>
      </div>
      <div class="message-body">
        <p><?=$message[2];?></p>
        <p class="message_time"><?=date("g:i a", strtotime($message[1]));?></p>
      </div>
    </div>
    <div class="spacer"></div>
    <?php
}

首先,您可以使用列表分配将组件拆分为单独的变量:

    list($user,$date,$time,$message) = explode(' ', substr(strchr($line,":"),1), 4);

那你可以通过简单的对比,看看日期是不是新的:

    if ($date != $last_date) {
       $last_date = $date;
    ?><div><?=$date?></div><?php
    }

您应该在循环之前声明 $last_date,但您可以保留其未定义的值。

只需记住您上次使用的日期,然后将其与 $message[0]

中的日期进行比较
<?php
$lastDate = NULL;

$chat = file("members/cdn/1/chats/9188.txt");
foreach($chat as $line) :
    $name = strchr($line,":",true);
    $message = explode(' ', substr(strchr($line,":"),1), 3);
    if($lastDate != $message[0]) :
        $lastDate = $message[0];
?>
    <div><?=$message[0];?></div>
<?php
    endif;
?>
    <div class="container">
      <div class="arrow">
        <div class="outer"></div>
        <div class="inner"></div>
      </div>
      <div class="message-body">
        <p><?=$message[2];?></p>
        <p class="message_time"><?=date("g:i a", strtotime($message[1]));?></p>
      </div>
    </div>
    <div class="spacer"></div>
<?php
endforeach;
?>