相对于created_at时间戳在对象中对数组进行分组

时间:2018-09-19 09:29:13

标签: php laravel

我有返回用户评论的JSON数据:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false,
    "created_at": "10/09/2018"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false,
    "created_at": "10/09/2018"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false,
    "created_at": "15/09/2018"
  }]

我想通过数组中对象的 created_at 属性将该数据分组。我希望数据看起来像具有数据数组的对象所在的位置,并且具有相同对象的日期 created_at

[
  {
    created_at: '10/09/2018',
    data: [
      {
        userId: 1,
        id: 1,
        title: 'delectus aut autem',
        completed: false,
        created_at: '10/09/2018'
      },
      {
        userId: 1,
        id: 2,
        title: 'quis ut nam facilis et officia qui',
        completed: false,
        created_at: '10/09/2018'
      }
    ]
  },
  {
    created_at: '15/09/2018',
    data: [
      {
        userId: 1,
        id: 3,
        title: 'fugiat veniam minus',
        completed: false,
        created_at: '15/09/2018'
      }
    ]
  }
]

我的代码按数组中的列名分组,但不按数据数组的对象分组。有想法吗?

$result = [];

foreach ($data as $item) {
    $column = $item[$by_column];
    unset($item[$by_column]);
    if (isset($result[$column])) {
        $result[$column][] = $item;
    } else {
        $result[$column] = array($item);
    }
}

2 个答案:

答案 0 :(得分:0)

这是您拥有的数组。您可以使用laravel collect辅助函数来达到您的要求。

$arr = [
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false,
    "created_at": "10/09/2018"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false,
    "created_at": "10/09/2018"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false,
    "created_at": "15/09/2018"
  }
];

$jsonObj = collect($arr);
$groupedArray = $jsonObj->groupBy("created_at");

dd($groupedArray->toArray());

在上面的示例中,您可以将数组转换为集合,然后可以通过助手功能使用集合分组,然后您将获得这样的输出

array(
  "10/09/2018" => [
    {
      "userId": 1,
      "id": 1,
      "title": "delectus aut autem",
      "completed": false,
      "created_at": "10/09/2018"
    },
    {
      "userId": 1,
      "id": 2,
      "title": "quis ut nam facilis et officia qui",
      "completed": false,
      "created_at": "10/09/2018"
    }
  ],
  "15/09/2018" => [
    {
      "userId": 1,
      "id": 3,
      "title": "fugiat veniam minus",
      "completed": false,
      "created_at": "15/09/2018"
    }
  ]
)

我认为这可以解决您的问题。

答案 1 :(得分:0)

您可以使用laravel的集合分组方法

$data->groupBy();