php - 来自MySQL查询的多维数组

标签 php mysql arrays multidimensional-array

我正在尝试使用 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] 值等等,最后一个array end_date 应该得到当前时间值,因为数组结束了。

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

最佳答案

这应该能满足您的需求:

$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);

关于php - 来自MySQL查询的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17859021/

相关文章:

php - 无法使用适当的字符集更新列

javascript - JS : Resizing canvas + redrawing elements on canvas

php - 将 ON DUPLICATE KEY UPDATE 与 2 个键一起使用

php - 从 post 到单个 mysql 行的数组

php - 使用 POST/GET 将数组从 Objective C 发送到 PHP

mysql - Laravel 查询生成器高级 wheres AND, OR

javascript - 我的脚本加载太晚

mysql - 备份所有数据库和www目录的Shell脚本

c - 在 C 中,为什么不能在声明后将字符串分配给 char 数组?

javascript - jQuery - 呈现大量可滚动数据的最佳方式