如何修复检查两个数字之间存在的一个值

时间:2019-03-27 07:01:30

标签: php

我需要检查两个数字类型值之间是否存在一个用户输入值,但是根据我的代码,它不起作用。我在下面解释我的代码。

$post_code=751011
$dataCed=[{"region_id":"4","zip_from":"754346","zip_to":"754346"},{"region_id":"4","zip_from":"754345","zip_to":"754345"},{"region_id":"4","zip_from":"754130","zip_to":"754230"},{"region_id":"3","zip_from":"226012","zip_to":"226025"},{"region_id":"2","zip_from":"751001","zip_to":"751030"},{"region_id":"1","zip_from":"1000","zip_to":"1500"}]
//echo json_encode($dataCed);
$flag=0;
foreach ($dataCed as $key => $value) {
    if ($post_code >= (int)$value['zip_from'] && $post_code <= (int)$value['zip_to']) {
        $flag=1;
        $reg_code=$value['region_id'];
        break;
    }
}
echo ($flag);exit;

在这里,我应该将flag value=1中的i.e-751011作为邮政编码(751001 & 751030出现,但是我得到的输出为0,这是错误的。因此,如何修复此代码,以便我可以得到正确的输出。

3 个答案:

答案 0 :(得分:1)

您提供的代码中似乎不正确,但是假设$dataCed是JSON数据,您可以这样做:

<?php

$post_code = 751011;
$dataCed = '[{"region_id":"4","zip_from":"754346","zip_to":"754346"},{"region_id":"4","zip_from":"754345","zip_to":"754345"},{"region_id":"4","zip_from":"754130","zip_to":"754230"},{"region_id":"3","zip_from":"226012","zip_to":"226025"},{"region_id":"2","zip_from":"751001","zip_to":"751030"},{"region_id":"1","zip_from":"1000","zip_to":"1500"}]';
$dataCed = json_decode($dataCed);

$flag = 0;

foreach ($dataCed as $key => $value) {
    $value = (array) $value;
    if ($post_code >= (int)$value['zip_from'] && $post_code <= (int)$value['zip_to']) {
        $flag=1;
        $reg_code=$value['region_id'];
        break;
    }
}

echo ($flag) . "<br>";
echo ($reg_code);
exit;

答案 1 :(得分:0)

尝试以下代码:

''

然后,您应该获得准确的输出。问题是您需要正确解码$post_code = 751011; $dataCed = '[{"region_id":"4","zip_from":"754346","zip_to":"754346"},{"region_id":"4","zip_from":"754345","zip_to":"754345"},{"region_id":"4","zip_from":"754130","zip_to":"754230"},{"region_id":"3","zip_from":"226012","zip_to":"226025"},{"region_id":"2","zip_from":"751001","zip_to":"751030"},{"region_id":"1","zip_from":"1000","zip_to":"1500"}]'; $myArray = json_decode($dataCed); $flag = 0; foreach ($myArray as $key => $value) { if ($post_code >= $value->zip_from && $post_code <= $value->zip_to) { $flag = 1; $reg_code = $value->region_id; break; } } echo ($flag); exit; 数组。

答案 2 :(得分:0)

您可以使用array_filter进行检查,如下所示。

<?php
$post_code = 751011;
$dataCed = '[{"region_id":"4","zip_from":"754346","zip_to":"754346"},{"region_id":"4","zip_from":"754345","zip_to":"754345"},{"region_id":"4","zip_from":"754130","zip_to":"754230"},{"region_id":"3","zip_from":"226012","zip_to":"226025"},{"region_id":"2","zip_from":"751001","zip_to":"751030"},{"region_id":"1","zip_from":"1000","zip_to":"1500"}]';
$dataCed = json_decode($dataCed);

$result = array_filter($dataCed, function($v1) use ($post_code){
    if ((int)$post_code >= (int)$v1->zip_from && (int)$post_code <= (int) $v1->zip_to) {
        return $v1;
    } 
});

$found = count($result) > 0 ? true : false;
var_dump($found); // This gives bool(true)