类似聊天记录将上下文都是同一个人放在一个List里

<?php
$arr = array(
    array("userId"=>1,"name"=>"A","content" => "I'm A"),
    array("userId"=>2,"name"=>"Jasonote","content" => "I'm Jasonote"),
    array("userId"=>3,"name"=>"B","content" => "I'm B"),
    array("userId"=>1,"name"=>"A","content" => "I'm A"),
    array("userId"=>2,"name"=>"Jasonote","content" => "I'm Jasonote"),
    array("userId"=>2,"name"=>"Jasonote","content" => "I'm Jasonote"),
    array("userId"=>2,"name"=>"Jasonote","content" => "I'm Jasonote"),
    array("userId"=>4,"name"=>"C","content" => "I'm C"),
);

$result = [];
$up = '';
$i = 0;
foreach ($arr as $k => $v) {
    $t = $v['userId'];
    if ($k < 1) {
        $result[$i][] = $v;
        $up = $t;
        $i++;
    }else{
        if ($t == $up) {
            $result[$i][] = $v;
        }else{
            $i++;
            $result[$i][] = $v;
        }
        $up = $t;
    }
}

echo json_encode(array_values($result));

[
    [
    {
      "userId":1,
      "name":"A",
      "content":"I'm A"
    }
  ],
  [
    {
      "userId":2,
      "name":"Jasonote",
      "content":"I'm Jasonote"
    }
  ],
  [
    {
      "userId":3,
      "name":"B",
      "content":"I'm B"
    }
  ],
  [
    {
      "userId":1,
      "name":"A",
      "content":"I'm A"
    }
  ],
  [
    {
      "userId":2,
      "name":"Jasonote",
      "content":"I'm Jasonote"
    },
    {
      "userId":2,
      "name":"Jasonote",
      "content":"I'm Jasonote"
    },
    {
      "userId":2,
      "name":"Jasonote",
      "content":"I'm Jasonote"
    }
  ],
  [
    {
      "userId":4,
      "name":"C",
      "content":"I'm C"
    }
  ]
]

Jason.wang

When you find your talent can't afford to be ambitious, be quiet and study !

You may also like...