求开发基于距离的动态计价函数,附计价规则与现有PHP代码
Fixed Tiered Distance-Based Pricing for Your PHP Code
First, let's clear up a small overlap in your original pricing rules (I’m assuming this was a typo to avoid conflicting tiers):
- 0-10km: ₹10/km
- 10-15km: ₹10/km
- 15-20km: ₹9/km
- 20-25km: ₹8.5/km
- 25-30km: ₹8/km
- 30-40km: ₹7.5/km
- 40km+ (including 50km and beyond): ₹7/km
Your current code has two critical issues blocking correct pricing:
- The
$kmvariable includes a'km'string suffix, so you can’t multiply it directly for calculations. - The pricing logic only uses a flat rate of 10 or 9, which doesn’t align with your tiered rules.
Here’s the optimized code with proper tiered pricing, plus better maintainability for future admin updates:
// Reusable function to calculate tiered ride price function calculateRidePrice(float $distance): float { // Define pricing tiers (easy to edit for admins later) $pricingTiers = [ ['min_km' => 0, 'max_km' => 10, 'rate' => 10.0], ['min_km' => 10, 'max_km' => 15, 'rate' => 10.0], ['min_km' => 15, 'max_km' => 20, 'rate' => 9.0], ['min_km' => 20, 'max_km' => 25, 'rate' => 8.5], ['min_km' => 25, 'max_km' => 30, 'rate' => 8.0], ['min_km' => 30, 'max_km' => 40, 'rate' => 7.5], ['min_km' => 40, 'max_km' => PHP_INT_MAX, 'rate' => 7.0] // Covers all distances over 40km ]; $totalPrice = 0.0; $remainingDistance = $distance; foreach ($pricingTiers as $tier) { if ($remainingDistance <= 0) break; // Calculate how much of the remaining distance falls into this tier $tierDistance = min($remainingDistance, $tier['max_km'] - $tier['min_km']); // Only charge if the distance is within the tier's range if ($distance > $tier['min_km']) { $totalPrice += $tierDistance * $tier['rate']; $remainingDistance -= $tierDistance; } } return $totalPrice; } foreach ($usersInfo as $index => $users) { $ridefrom = $users['ride_from']; $rideto = $users['ride_to']; // Parse latitude/longitude coordinates $tempLatLong = explode(',', $ridefrom); $tempLatLong1 = explode(',', $rideto); $key = ['lat', 'long']; $to = array_combine($key, $tempLatLong); $from = array_combine($key, $tempLatLong1); // Calculate distance and extract numeric value (remove 'km' suffix) $distanceStr = distanceCalculation($from['lat'], $from['long'], $to['lat'], $to['long']); $km = (float) str_replace('km', '', trim($distanceStr)); // Convert to pure number for calculations $usersInfo[$index]['distance'] = $km . 'km'; // Store with unit for display // Calculate tiered price $price = calculateRidePrice($km); // Optional: Format price to 2 decimal places for currency $usersInfo[$index]['price'] = number_format($price, 2); } return $usersInfo;
Key Improvements:
- Fixed Distance Handling: We extract the numeric value of the distance first, so arithmetic operations work correctly.
- Encapsulated Pricing Logic: The
calculateRidePrice()function keeps tiered rules separate from the main loop, making it easy to update rates or add new tiers later. - Accurate Tier Calculation: The function splits the ride distance into each tier, ensuring you charge the correct rate for every segment of the journey.
- Maintainability: Admins can edit the
$pricingTiersarray directly (or you can move it to a config file/database) without rewriting core code.
Optional Enhancements:
- Store the
$pricingTiersarray in a database or config file so admins can edit rates via a backend UI. - Add validation for invalid distance values (e.g., negative numbers) in the
calculateRidePrice()function. - Round the final price to the nearest whole number if needed for your currency setup.
内容的提问来源于stack exchange,提问作者new developer
相关产品推荐
相关产品推荐

