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

时间:2016-05-09 14:06:21

标签: php loops skip

这是一个文本文件内容,它将是聊天数据库

  你好:2016-05-02 11:41:53嗨

     

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

     你好:2016-05-02 11:43:33你好吗?

     

穆罕默德:2016-05-02 14:44:56我很好!

这是循环获取内容的代码

<?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
}
?>

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

3 个答案:

答案 0 :(得分:1)

只需记住您上次使用的日期,然后将其与doRequest(input).success {result in print("success, with:", result) }.failure { print("fail :(") }

中的日期进行比较
doSomethingAsynchronous

答案 1 :(得分:0)

试试这个:

$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
}

答案 2 :(得分:0)

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

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

然后您可以使用简单的比较来查看日期是否为新的:

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

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