如果最后一个来自同一用户,则对邮件进行分组

时间:2014-09-18 19:03:57

标签: php

我聊天,消息的印刷或多或少是这样的:

  Jhon:嘿!

     

Jhon:好吗?

     史密斯:是的,我很好。感谢。

     

Jhon:太好了!

打印我有代码:

array(4) {
  [0]=>
  array(3) {
    ["from"]=>
    string(4) "Jhon"
    ["to"]=>
    string(5) "Smith"
    ["msg"]=>
    string(4) "Hey!"
  }
  [1]=>
  array(3) {
    ["from"]=>
    string(4) "Jhon"
    ["to"]=>
    string(5) "Smith"
    ["msg"]=>
    string(5) "Fine?"
  }
  [2]=>
  array(3) {
    ["from"]=>
    string(5) "Smith"
    ["to"]=>
    string(4) "Jhon"
    ["msg"]=>
    string(23) "Yeah, I'm fine. Thanks."
  }
  [3]=>
  array(3) {
    ["from"]=>
    string(4) "Jhon"
    ["to"]=>
    string(5) "Smith"
    ["msg"]=>
    string(12) "That's nice!"
  }
}

我想要显示如下消息:

  Jhon:嘿!

     

精细?

     史密斯:是的,我很好。感谢。

     

Jhon:太好了!

谢谢你,对不起我的英语。

1 个答案:

答案 0 :(得分:0)

一个让你入门的小例子:

<?php

$messages = array(
    array(
        "From" => "A",
        "To" => "B",
        "Msg" => "A first message"
    ),
    array(
        "From" => "A",
        "To" => "B",
        "Msg" => "A second message"
    ),
    array(
        "From" => "B",
        "To" => "A",
        "Msg" => "B first message"
    )
);

$previousSender = null;
foreach($messages as $message) {
    if($previousSender == null || $previousSender != $message["From"])
        printf("%s: %s", $message["From"], $message["Msg"]);
    else
        printf("%s", $message["Msg"]);  

    $previousSender = $message["From"];
}

?>