Laravel系列定制

时间:2017-09-02 18:01:08

标签: php arrays

给定这样的数组,我想以自定义方式排列数据。

$data = [
    "block" => [
        [
            "message" => "Message number 1 for first conversation",
            "is_seen" => 0,
            "user_id" => 2,
            "sent_time" => "2017-08-30 23:28:50"
        ]
    ],
    "block" => [
        [
            "message" => "Message number 2 for first conversation",
            "is_seen" => 1,
            "user_id" => 1,
            "sent_time" => "2017-08-29 23:36:27"
        ],
        [
            "message" => "Message number 3 for first conversation",
            "is_seen" => 1,
            "user_id" => 1,
            "sent_time" => "2017-08-29 23:36:27"
        ]
    ],
   "block" => [
        [
            "message" => "Message number 4 for first conversation by second user",
            "is_seen" => 1,
            "user_id" => 2,
            "sent_time" => "2017-08-29 23:36:27"
        ],
        [
            "message" => "Message number 5 for first conversation by second user",
            "is_seen" => 1,
            "user_id" => 2,
            "sent_time" => "2017-08-29 23:36:27"
        ]
    ]
];

我想要做的是对同一用户发送的消息进行分组,这样我得到一个这样的数组:

user_id

基本上,如果下一条消息user_id与之前的消息group相同,则将其添加到组数组中。如果不是,请创建新的client.transport.session.headers.update({'yourHeader': 'yourValue'}) 数组,依此类推。我不想将所有用户消息组合在一起,因为前端的分页需要此结构。

2 个答案:

答案 0 :(得分:1)

你可以这样做

 $new = array();
 $prev = "";
 $count =0;
 foreach($arr as $key=> $value){
    if($prev == $value["user_id"]){
      $new[$count-1][] = $value;
    }else {
      $new[$count][] = $value;
      $count++;
    }$prev = $value["user_id"];
}
print_r($new);

现场演示:https://eval.in/854288

答案 1 :(得分:0)

首先,您不能将重复的关联键放入同一个数组中,但是,您可以按以下方式按照某些序列号对块进行分组:

[
     "block_0" => [
       [
         "message" => "Message number 1 for first conversation",
         "is_seen" => 0,
         "user_id" => 2,
         "sent_time" => "2017-08-30 23:28:50",
       ],
     ],
     "block_1" => [
       [
         "message" => "Message number 2 for first conversation",
         "is_seen" => 1,
         "user_id" => 1,
         "sent_time" => "2017-08-29 23:36:27",
       ],
       [
         "message" => "Message number 3 for first conversation",
         "is_seen" => 1,
         "user_id" => 1,
         "sent_time" => "2017-08-29 23:36:27",
       ],
     ],
     "block_2" => [
       [
         "message" => "Message number 4 for first conversation by second user",
         "is_seen" => 1,
         "user_id" => 2,
         "sent_time" => "2017-08-29 23:36:27",
       ],
       [
         "message" => "Message number 5 for first conversation by second user",
         "is_seen" => 1,
         "user_id" => 2,
         "sent_time" => "2017-08-29 23:36:27",
       ],
     ],
   ]

结果应该是:

TaskBarIcon