取消设置数组中的键后出现非法偏移量?

Illegal offset after unsetting a key in an array?

我有一个数组 $data_list,其中包含一个元素 date_time,其数据格式如下:

[0]=>
  array(2) {
    ["date_time"]=>
    string(19) "2014-11-14 09:30:03"
    ["follower_count"]=>
    string(4) "1567"
  }

实际上这里是 $data_list 中的全部数据:http://pastebin.com/wA7f9Aet

我想将 date_time 元素一分为二,所以看起来像这样:

[0]=>
      array(2) {
        ["date"]=>
        string(19) "2014-11-14"
        ["date"]=>
        string(5) "09:02"
        ["follower_count"]=>
        string(4) "1567"
      }

请注意,date_time 元素已拆分,时间部分也已缩短为 HH:MM

我有以下循环遍历我的数组 $data_list 并列出了每一行 应该 做什么。

foreach ($data_list as &$data) {
        $datetime = new DateTime($data['date_time']); // creates new var
        $date = $datetime->format('Y-m-d'); // formats the date portion
        $time = $datetime->format('H:i'); // formats the time portion
        unset($data['date_time']); // Removes the old date_time element
        array_push($data_list,$time); // adds new time element
        array_push($data_list,$date); // adds new date element
    }
  1. 遍历 $data_list 调用每个数组元素 $data
  2. 创建 $datetime
  3. 的新变量
  4. 仅格式化这部分的日期
  5. 只格式化这部分的时间
  6. 删除旧的 $date_time 元素
  7. 添加新的 $time 元素
  8. 添加一个 $date 元素

这在 array_push 行之前工作正常。我不知道为什么。我收到以下错误:

Warning: Illegal string offset 'date_time' in /Applications/MAMP/path on line 70

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (0) at position 0 (0):

我不明白为什么它会在 array_push 部分掉下来。在我看来它正在尝试调用现在未设置的 date_time 元素,但为什么呢?

添加了 $key 来检测数组的确切索引,以便您可以将 datetime 推入相同的 index

foreach ($data_list as $key=>&$data) {
    $datetime = new DateTime($data['date_time']); // creates new var
    $date = $datetime->format('Y-m-d'); // formats the date portion
    $time = $datetime->format('H:i'); // formats the time portion
    unset($data['date_time']); // Removes the old date_time element
    array_push($data_list[$key],$time); // adds new time element
    array_push($data_list[$key],$date); // adds new date element
}