PHP按时间排序函数sort_by_time出现Undefined offset错误求助
sort_by_time Function Hey there, let's break down this frustrating offset error you're stuck on—those undefined index bugs are such a pain, especially when dealing with dynamic data. Let's walk through the fixes step by step:
First, Understand the Root Cause
The Undefined offset: 0/1/2 error means you're trying to access an array index that doesn't exist. For example, if you split a time string into $_time but the string is malformed (like missing colons, or being empty), the array will have fewer than 3 elements, so $_time[0] or $_time[2] won't exist.
Step 1: Validate Your Dynamic Time Data
First, confirm your dynamically generated time strings are in the format your function expects (I'm guessing something like HH:MM:SS). Add a quick debug check to see what's actually coming in:
// Right before passing time data to your function var_dump($your_dynamic_time_list);
Look for entries that are empty, null, or missing parts (like 14:30 instead of 14:30:00). These broken entries are the source of your errors.
Step 2: Add Defensive Checks to Your Function
Don't assume every time string will split into a 3-element array. Update your sort_by_time function to validate input first:
function sort_by_time($time1, $time2) { // Split times and validate the result $timeParts1 = explode(':', $time1); $timeParts2 = explode(':', $time2); // Check if both time strings split into valid 3-part arrays if (count($timeParts1) !== 3 || count($timeParts2) !== 3) { // Log the bad data for debugging error_log("Invalid time format detected: '$time1' or '$time2'"); // Return a safe default (adjust based on your sorting logic) return 0; } // Now safely calculate total seconds for comparison $totalSec1 = (int)$timeParts1[0] * 3600 + (int)$timeParts1[1] * 60 + (int)$timeParts1[2]; $totalSec2 = (int)$timeParts2[0] * 3600 + (int)$timeParts2[1] * 60 + (int)$timeParts2[2]; // Swap logic: return 1 if time2 should come before time1 (for usort) return $totalSec2 > $totalSec1 ? 1 : -1; }
Step 3: Fix the Dynamic Time Generation
Once you've identified which time entries are broken, go back to the code that generates them:
- If pulling from a database, check if time fields allow null values—add a default (like
00:00:00) for empty entries. - If generating via code, ensure all branches produce a complete
HH:MM:SSstring (even if seconds are00).
Bonus: Debug Specific Error Cases
If you still can't pinpoint the issue, add targeted checks right before the error line:
// Right before accessing $_time[0] if (!isset($_time[0])) { echo "Broken time string: $originalTimeString"; var_dump($_time); die(); // Pause to inspect the bad data }
This will show you exactly which time entry is causing the problem.
内容的提问来源于stack exchange,提问作者hihihihi

