我正试图建立一个自定义的邮政编码搜索来查找配送费,但我似乎做不好。
首先,这是我如何在前端设置我的表单:
<form class="delivery-fee" role="search" method="get" action="">
<div class="form-group">
<label>Find Your Delivery Area:</label>
<input class="form-control" type="number" value="" name="zipcode" placeholder="Enter Zipcode" pattern="d*" />
<input type="submit" value="See Delivery Minimum" />
</div>
</form>
我的数据设置如下:
$delivery_areas = [
'Rancho Cucamonga' => [
'zipcodes' => [91701, 91729, 91730, 91737, 91739],
'fee' => 100
],
'Upland' => [
'zipcodes' => [91784, 91785, 91786],
'fee' => 150
]
];
这就是我循环浏览数据的方式:
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area)) {
if (in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
echo $delivery_area['fee'];
} else {
echo 'Error message';
}
}
}
我遇到的问题是,如果我搜索91701,我确实会返回正确的费用,但我也会收到错误消息。另一方面,如果没有找到,我还会收到两条错误消息。
关于如何才能达到预期效果,有什么建议吗?
您可以使用var来调整代码,例如:
$fee = -1;
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area)) {
if (in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
$fee = $delivery_area['fee'];
break;
}
}
}
if($fee == -1)
echo 'Error message';
else
echo $fee;
测试:
$fee = 0;
foreach ($delivery_areas as $key => $delivery_area) {
if (is_array($delivery_area) && in_array($_GET['zipcode'], $delivery_area['zipcodes'])) {
$fee = $delivery_area['fee']; break;
}
}
echo $fee!=0 ? $fee : 'Error Message';