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

PHP实现按指定次数拆分一天时间的函数需求

Solution for PHP split_times() Function

I've put together a robust PHP function that exactly meets your requirement of splitting a 24-hour day into specified intervals and returning the formatted time array. Here's how it works:

Approach

  1. Input Validation: First, we check that the input is a positive integer to avoid invalid splits.
  2. Calculate Interval: Convert the 24-hour day into total seconds (86400), then divide by the number of intervals to get the step size in seconds.
  3. Generate Times: Loop through each interval, calculate the corresponding time in seconds from the start of the day, then format it into HH:MM:SS using gmdate() (to avoid timezone discrepancies).

The Function Code

function split_times($interval) {
    // Ensure we're working with a valid positive integer
    if (!is_int($interval) || $interval <= 0) {
        return [];
    }
    
    $timeArray = [];
    $totalDailySeconds = 24 * 3600; // Total seconds in a day
    $stepSeconds = $totalDailySeconds / $interval;
    
    for ($i = 0; $i < $interval; $i++) {
        // Calculate seconds from midnight for the current interval
        $currentSeconds = $i * $stepSeconds;
        // Format to HH:MM:SS (gmdate avoids timezone shifts)
        $timeArray[] = gmdate('H:i:s', $currentSeconds);
    }
    
    return $timeArray;
}

Test Examples

Let's verify with your provided cases:

  • split_times(2) returns: ['00:00:00', '12:00:00']
  • split_times(4) returns: ['00:00:00', '06:00:00', '12:00:00', '18:00:00']
  • split_times(6) returns: ['00:00:00', '04:00:00', '08:00:00', '12:00:00', '16:00:00', '20:00:00']

This function also handles non-divisible intervals gracefully. For example, split_times(5) would return:
['00:00:00', '04:48:00', '09:36:00', '14:24:00', '19:12:00']

Key Notes

  • Using gmdate() ensures that we don't get timezone offsets (e.g., if your server is in a UTC+X timezone, date() would shift the midnight time).
  • The input validation ensures the function doesn't break with invalid inputs like 0, negative numbers, or non-integers.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:29:12