You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用给定变量生成按日期循环的PHP多维数组

Solution for Generating Daily Allocation Array

Hey there! Let's figure out how to build that multi-dimensional array you need by looping through each date between your start and due dates. Using PHP's DateTime class is the cleanest approach here—no messy manual date calculations to worry about.

Step-by-Step Code Implementation

<?php
// Your provided variables
$start_date = "2018-01-01";
$start_time = "01:30 PM";
$due_date = "2018-01-03";
$due_time = "11:30 AM"; // Don't forget this variable from your input!
$project = "10001";
$assign_to = "G2E0357";

// Initialize empty array to hold our final result
$allocationArray = [];

// Convert start and end dates to DateTime objects for easy manipulation
$currentDate = new DateTime($start_date);
$endDate = new DateTime($due_date);

// Loop through each date (including both start and end dates)
do {
    // Add a new entry for the current date
    $allocationArray[] = [
        'allocation_date' => $currentDate->format('Y-m-d'),
        't_project'       => $project,
        't_assign_to'     => $assign_to,
        't_start_time'    => $start_time,
        't_end_time'      => $due_time
    ];

    // Increment the current date by 1 day for the next iteration
    $currentDate->modify('+1 day');
} while ($currentDate <= $endDate);

// Output the result to verify
print_r($allocationArray);
?>

Key Details to Note

  • DateTime Class Usage: This handles all the date logic for us—no need to parse strings or calculate days manually. It even accounts for months with different days or leap years if you ever need to expand the date range.
  • do-while Loop: We use this instead of a while loop to ensure that even if the start and end dates are the same, we still generate one entry.
  • Consistent Data: Each entry in the array uses your original variables for project, assignee, start time, and end time, while updating only the allocation_date for each day in the range.

When you run this code, you'll get exactly the array structure you asked for:

Array
(
    [0] => Array
        (
            [allocation_date] => 2018-01-01
            [t_project] => 10001
            [t_assign_to] => G2E0357
            [t_start_time] => 01:30 PM
            [t_end_time] => 11:30 AM
        )

    [1] => Array
        (
            [allocation_date] => 2018-01-02
            [t_project] => 10001
            [t_assign_to] => G2E0357
            [t_start_time] => 01:30 PM
            [t_end_time] => 11:30 AM
        )

    [2] => Array
        (
            [allocation_date] => 2018-01-03
            [t_project] => 10001
            [t_assign_to] => G2E0357
            [t_start_time] => 01:30 PM
            [t_end_time] => 11:30 AM
        )

)

内容的提问来源于stack exchange,提问作者Mithun M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:05:52