2013-07-25 42 views
0

我试图创建多维数组start_dateend_date的多维数组

$array = []; 
$i = 0; 

while ($row = mysqli_fetch_assoc($result)) { 
    $array[$i]['start_date'] = $row['current_status_start_time']; 
    $array[$i]['end_date'] = ''; 
    $i++; 
} 
print_r($array); 

这将返回我数组是这样的:

Array ( 
    [0] => Array (
     [start_date] => 2013-07-25 11:18:42 
     [end_date] =>) 
    [1] => Array (
     [start_date] => 2013-07-26 05:24:08 
     [end_date] =>) 
    [2] => Array ( 
     [start_date] => 2013-07-31 17:25:05 
     [end_date] =>) 
) 

end_date应该得到下一个阵列[start_date]节点值:

 Array ( 
    [0] => Array (
     [start_date] => 2013-07-25 11:18:42 
     [end_date] => **2013-07-26 05:24:08**) 
    [1] => Array (
     [start_date] => **2013-07-26 05:24:08** 
     [end_date] => 2013-07-31 17:25:05) 
    [2] => Array ( 
     [start_date] => 2013-07-31 17:25:05 
     [end_date] => current_date) 
) 

正如您在上一个代码示例中看到的那样,array[0][end_date]应该得到array[1][start_date]值等,最后一个数组end_date应该得到当前时间值,因为有数组尾。

我应该使用第二个循环来实现吗?还是有其他更简单的方法?

回答

2

这应该得到你想要的东西:

$array = []; 
$i = 0; 

while ($row = mysqli_fetch_assoc($result)) { 
    $array[$i]['start_date'] = $row['current_status_start_time']; 
    $array[$i]['end_date'] = ''; 
    if ($i > 0){ 
     // if we are pass the first item set the previous item to the current start date 
     $array[$i-1]["end_date"] = $array[$i]['start_date']; 
    } 
    $i++; 
} 
// fill in the last end_date with the current_date 
$array[$i]["end_date"] = date("Y-m-d H:i:s"); 
print_r($array); 
+0

超级!谢谢 :) – DeividasJJ

1

我会用一个循环去。就像这样:

foreach($mainArray as $key => $value) 
{ 
    $next = $key + 1; 

    if(!is_null($mainArray[$next]['start_date'])) 
    { 
     $mainArray[$key]['end_date'] = $mainArray[$next]['start_date']; 
    } 
    else 
    { 
     $mainArray[$key]['end_date'] = current_date; 
    } 
} 

print_r($main_array);