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

PHP实现按分钟计算停车时长收费功能的技术咨询

Fixing Your Parking Fee Calculation Function

Hey there! Let's get your parking fee calculator working reliably for any duration, not just the first two hours. First, let's break down the gaps in your current code:

  • It hardcodes the parking time as 10 minutes, so it can't handle different input values.
  • It only accounts for durations under 2 hours—anything over 120 minutes will throw an error because $time_parked isn't defined in that case.
  • The return statements inside your if/elseif blocks mean the final echo line will never run (the function exits before reaching it).

Here's the Improved Solution

Based on your requirements:

  • $50 for 1 hour (or less)
  • $100 for the 1–2 hour interval
  • $200 for 2–3 hours, and so on (each additional hour interval doubles the fee)

We can create a reusable, dynamic function that handles all scenarios:

function calculateParkingFee(int $minutes): float {
    $baseRate = 50.0;
    
    // Ensure we use at least 1 interval (even for 0 minutes, per your "1 hour (含)以内" rule)
    $hourIntervals = max(1, ceil($minutes / 60));
    
    // Calculate fee: each interval after the first doubles the base rate
    $totalFee = $baseRate * (2 ** ($hourIntervals - 1));

    echo "Amount to pay: $" . number_format($totalFee, 2) . "\n";
    return $totalFee;
}

// Test with different parking durations
calculateParkingFee(10);   // Output: Amount to pay: $50.00
calculateParkingFee(60);   // Output: Amount to pay: $50.00
calculateParkingFee(61);   // Output: Amount to pay: $100.00
calculateParkingFee(120);  // Output: Amount to pay: $100.00
calculateParkingFee(121);  // Output: Amount to pay: $200.00
calculateParkingFee(240);  // Output: Amount to pay: $400.00
calculateParkingFee(0);    // Output: Amount to pay: $50.00

Key Details Explained:

  • Parameterized Input: The function accepts $minutes as an argument, so you can pass any parking duration instead of hardcoding it.
  • Interval Calculation: ceil($minutes / 60) rounds up minutes to the next full hour interval (e.g., 61 minutes becomes 2 intervals for the 1–2 hour window). Using max(1, ...) ensures even 0 minutes uses the 1-hour interval rule.
  • Doubling Logic: 2 ** ($hourIntervals - 1) handles the fee doubling: for 1 interval, it’s 2^0 = 1 ($50), for 2 intervals it’s 2^1 = 2 ($100), and so on.
  • Clean Currency Output: number_format() formats the fee to two decimal places, matching standard currency display.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:35:15