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

时间:2015-01-27 11:05:52

标签: php arrays datetime

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

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

事实上,这里是$data_listhttp://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. 添加ne $date元素
  9. 直到array_push行才能正常工作。我无法理解为什么。我收到以下错误:

      

    警告:非法字符串偏移' date_time' in / Applications / MAMP /第70行路径

         

    致命错误:未捕获的异常'异常' with message' DateTime :: __ construct():无法解析位置0(0)的时间字符串(0):

    我无法理解为什么它会在array_push部分摔倒。在我看来,它似乎试图调用现在未设置的date_time元素,但为什么呢?

1 个答案:

答案 0 :(得分:1)

添加$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
}
相关问题