取一个数组并将其转换为一个新数组

时间:2013-07-26 07:12:47

标签: php arrays

我有以下数组:

[timestamps => Array ( 
    [0] => 2013-07-25 18:02:48 
    [1] => 2013-07-25 19:12:07 
    [2] => 2013-07-25 19:13:09 
) 

我需要把它变成这个:

$date_accessed  = array(
    array( 'ID' => 1, 'date' => '2013-07-25', 'time' => '18:02:49' ),
    array( 'ID' => 2, 'date' => '2013-07-25', 'time' => '19:12:07' ),
    array( 'ID' => 3, 'date' => '2013-07-25', 'time' => '19:13:09' )
);

我正在使用此Wordpress函数生成数组:

get_user_meta( $user_id, '_last_login', true )

ID键的值递增,而不是从timestamp数组键派生。例如,要生成ID值,可以将其作为$ i = 1 ... $ i ++。

我需要从样本数组中分别提取日期和时间,并将值分配给日期和时间键。

我已经尝试了但是我不能把它全部拉到一起。

3 个答案:

答案 0 :(得分:0)

<?php
    $timestamps = array ('2013-07-25 18:02:48', '2013-07-25 19:12:07', '2013-07-25 19:13:09');
    $arr=array();
    $i=0;
    foreach($timestamps as $key=>$timestamp) {
        $time = explode(" ", $timestamp); //you better be sure its a timestamp
        $arr[$i] = array('ID' => $key, 'date'=>$time[0], 'time'=>$time[1]);
        $i++;
    }
    print_r($arr);
?>

答案 1 :(得分:0)

$timestamps = array ('2013-07-25 18:02:48', '2013-07-25 19:12:07', '2013-07-25 19:13:09');

$newArr = array();
$i = 0;
foreach($timestamps as $arr) {
    $datetime = new DateTime($arr);
    $newArr[$i]['ID']   = $i; // set index with $i
    $newArr[$i]['date'] = date_format($datetime, 'Y-m-d'); // get date
    $newArr[$i]['time'] = date_format($datetime, 'H:i:s'); // get time
    $i++;
}

输出

array (size=3)
  0 => 
    array (size=3)
      'ID' => int 0
      'date' => string '2013-07-25' (length=10)
      'time' => string '18:02:48' (length=8)
  1 => 
    array (size=3)
      'ID' => int 1
      'date' => string '2013-07-25' (length=10)
      'time' => string '19:12:07' (length=8)
  2 => 
    array (size=3)
      'ID' => int 2
      'date' => string '2013-07-25' (length=10)
      'time' => string '19:13:09' (length=8)

答案 2 :(得分:0)

$date_accessed = array();
foreach ($timestamps as $key => $value){
    $dt = explode(' ', $value);
    $date_accessed[] = array('ID' => $key, 'date' => $dt[0], 'time' => $dt[1]);
}