判断多个区间是否有交集

 '1', 'act_price_z' => '10'],
        ['act_price_a' => '20', 'act_price_z' => '30'],
        ['act_price_a' => '31', 'act_price_z' => '40'],
];
$actprice = [];
foreach ($a as $_v) {
    if (isset($_v['act_price_a']) && isset($_v['act_price_z'])) {
        $actprice[$_v['act_price_a']] = $i;
        $actprice[$_v['act_price_z']] = $i++;
    }
}
ksort($actprice);
if ((($i - 1) * 2) > count($actprice)) {
    echo '预售定金规则活动价区间有交叉,请检查重填';
}
$tmp = '';
$difTime = 0;
foreach ($actprice as $item) {
    if ($tmp == '') {
        $tmp = $item;
    } else {
        if ($tmp == $item) {
            $tmp = $item;
            $difTime = 0;
        } else {
            $tmp = $item;
            $difTime++;
            if ($difTime >= 2) {
                echo '预售定金规则活动价区间有交叉,请检查重填';
                break;
            }
        }
    }
}

方法封装

/*
 * 判断多个区间是否呦交集
 * @param array 区间数组
 * @param $key1 string
 * @param $key2 string
 * @return bool 有交集返回true
 */
function isOverlapOfMoreRange($data, $key1 = '0', $key2 = '1') {
    $i = 1;
    $list = [];
    $tmp = '';
    $difTime = 0;
    foreach ($data as $_v) {
        if ($key1 === '0') {
            $_v = array_values($_v);
        }
        if (isset($_v[$key1]) && isset($_v[$key2])) {
            $list[$_v[$key1]] = $i;
            $list[$_v[$key2]] = $i++;
        }
    }
    ksort($list);
    if ((($i - 1) * 2) > count($list)) {
        return true;
    }
    foreach ($list as $item) {
        if ($tmp == '') {
            $tmp = $item;
        } else {
            if ($tmp == $item) {
                $tmp = $item;
                $difTime = 0;
            } else {
                $tmp = $item;
                $difTime++;
                if ($difTime >= 2) {
                    return true;
                    break;
                }
            }
        }
    }
    return false;
}

调用

$a = [
        ['act_price_a' => '1', 'act_price_z' => '10'],
        ['act_price_a' => '20', 'act_price_z' => '30'],
        ['act_price_a' => '31', 'act_price_z' => '40'],
];
if (isOverlapOfMoreRange($a, 'act_price_a', 'act_price_z')) {
    echo '有交集';
}

你可能感兴趣的:(算法复杂度)