【问题标题】:How to group array data by date如何按日期对数组数据进行分组
【发布时间】:2015-11-26 22:08:59
【问题描述】:

我使用的 API 的端点结果如下所示:

[
    {
        placeId: 1,
        startDateIso: "2015-11-26T12:00:00+0100",
    },
    {
        placeId: 1,
        startDateIso: "2015-11-26T13:00:00+0100",
    },
    {
        placeId: 1,
        startDateIso: "2015-11-27T10:00:00+0100",
    },
    {
        placeId: 1,
        startDateIso: "2015-11-27T11:00:00+0100",
    },
]

我如何对这个 JSON 数组进行排序以获得这样的输出:

{
   [
       {
           placeId: 1,
           startDateIso: "2015-11-26T12:00:00+0100",
       },
       {
           placeId: 1,
           startDateIso: "2015-11-26T13:00:00+0100",
       }
   ],

   [
       {
           placeId: 1,
           startDateIso: "2015-11-27T10:00:00+0100",
       },
       {
           placeId: 1,
           startDateIso: "2015-11-27T11:00:00+0100",
       }
   ]
}

我想按日期对数据进行排序,并为每个数据创建一个数组。

【问题讨论】:

  • 如何使用 API?您想在哪里以及如何进行排序?
  • 如果您需要帮助,请显示您的代码 .. 仅需要的输出是不够的 ..
  • 您想要的 JSON 输出也无效

标签: php arrays json sorting slim


【解决方案1】:

尝试关注

// Sample input
$input = array(array('startDateIso'=>'2015-11-26T12:00:00+010', 'placeId'=>1),
               array('startDateIso'=>'2015-11-26T12:00:00+010', 'placeId'=>2),
               array('startDateIso'=>'2015-11-27T12:00:00+010', 'placeId'=>3),
               array('startDateIso'=>'2015-11-27T13:00:00+010', 'placeId'=>4));

$output = array();

foreach($input as $element) {
    $date = date('d.m.Y', strtotime($element['startDateIso'])); // Truncate time

    $output[$date][] = $element; // Group using associate array, key is the date
}

$result = array_values($output); // Converts assoicate array to array

echo json_encode($result);

输出:

[
     [
          {
               "startDateIso":"2015-11-26T12:00:00+010",
               "placeId":1
          },
          {
               "startDateIso":"2015-11-26T12:00:00+010",
               "placeId":2
          }
     ],
     [
          {
               "startDateIso":"2015-11-27T12:00:00+010",
               "placeId":3
          },
          {
               "startDateIso":"2015-11-27T13:00:00+010",
               "placeId":4
          }
     ]
]

【讨论】:

  • 嗨@bltstray 如果这个或任何答案已经解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 2019-03-05
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
相关资源
最近更新 更多