我正在使用Google Distance Matrix来计算出租车网站的两个位置之间的距离。我需要测试一个条件,以确定其中一个位置是否是伦敦机场,如果是,则返回一条消息,而不是计算行程的成本。
它在昨天和今天工作得很好......代码已经变得很苛刻了。如果接送和送货地点都是机场,它只返回信息,但如果只有一个,则计算全距离的费用,这违背了我的目的。下面是代码结构,我想知道当我启动strpos()测试时,我是否在第39行使用了错误的嵌套条件语法....
if (isset($_POST['submitted'])):
$origin = urlencode($_POST['origin']);
$destination = urlencode($_POST['destination']);
// Insert encoded url variables
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destination&mode=driving&keyy={API KEY}";
$json = file_get_contents($url); // get the data from Google Maps API
$status = $result['rows'][0]['elements'][0]['status'];
if (status is OK):
// Calculate the distance
$status = ...;
$DistanceMetres = .....;
$Distance = .....; // converted to yards
// Calculate the Day Rate
....
// Calculate the Night Rate
....
// Calculate the Sunday Rate
....
// Calculate the Christmas & NYE Rate
....
// Set up variables for pick-up & drop-off locations
$toairport = $result['destination_addresses'][0];
$fromairport= $result['origin_addresses'][0];
if (distance is the minimum distance) {
echo the minimum cost of the trip
} else { //ie if the distance is more than the minimum distance
// Check to see if pick-up or drop-off destination is an airport
if (strpos($toairport, 'Heathrow') || strpos($toairport, 'Gatwick') || strpos($toairport, 'London Luton') || strpos($toairport, 'London City Airport') || strpos($fromairport, 'Heathrow') || strpos($fromairport, 'Gatwick') || strpos($fromairport, 'London Luton') || strpos($fromairport, 'London City Airport') === false) {
echo the cost of the trip
// But if at least one location is an airport
} else {
echo a message saying a special flat rate is available for airport transfers
}
}
else:
echo that status is not okay
endif;
else:
display input form
endif;
答案 0 :(得分:0)
我建议将检查作为一个函数来实现。例如
/**
* Check if the location is an airport.
*
* @param string $location
* @return bool
*/
function isAirport($location)
{
$airportList = ['Heathrow', 'Gatwick', 'London Luton', 'London City Airport'];
foreach ($airportList as $airport) {
if (strpos($location, $airport) !== false) {
return true;
}
}
return false;
}
请注意,我们使用strpos
运算符将false
结果与!==
进行比较,因为strpos
可能会返回零==
到false
。< / p>
接下来,内部检查可能如下所示
if (isAirport($toairport) || isAirport($fromairport)) {
echo 'a message saying a special flat rate is available for airport transfers'.PHP_EOL;
} else {
echo 'the cost of the trip'.PHP_EOL;
}
请注意,我们检查$toairport
是$ fromairport`变量是机场位置。我想这就是你希望脚本做的事情。
当我们使用这样的函数时,它非常容易阅读脚本并理解它在做什么。此外,它还可以通过添加新位置或改进逻辑来更轻松地修改脚本。例如,我们可能希望使检查用例不敏感。