确保范围值不与现有范围重叠 [英] Make sure range value doesn't overlap with existing ranges

查看:124
本文介绍了确保范围值不与现有范围重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中以min_age和max_age的形式存储了一些范围信息,例如:

I have some range information stored in a database as min_age and max_age, for example:

id      min_age     max_age
1       10          14
2       15          16
3       17          20

我想使用PHP(或MySql)进行一些验证,以便在创建另一个记录之前,我们确保范围不与现有范围重叠.因此,id = 4,min_age = 21,max_age = 25会很好,但是id = 4,min_age = 20,max_age = 25会失败.到目前为止,我的(伪)代码:

I want to do some validation using PHP (or MySql) so that, before another record is created, we make sure that the range doesn't overlap with an existing range. So, id=4, min_age=21, max_age=25 would be fine, but id=4, min_age=20, max_age=25 would fail. My (psuedo)code, thusfar:

$age['min'] = $x;
$age['max'] = $y;
$current ranges = db_query('SELECT min_age, max_age FROM age_table')->fetchAll();
foreach ($age as $limit)
{
    for ($i = 0; $i < count($current_ranges); $i++)
    {
        if ($limit >= $current_ranges[$i]->min_age && $limit <= $current_ranges[$i]->max_age) $conflict = $result[$i]->entity_id;
    }
}
    if ($conflict) fail();

但这是一个过分的简化(不是吗?),因为它只是测试以查看最小/最大值是否在定义的范围内.我认为这可能有效,但是我使用了一些模糊逻辑...有人可以帮助我进一步完善吗?干杯...

But this is an oversimplification (isn't it?), as it just tests to see if the min/max values fall within the defined ranges. I think this may work but employs some fuzzy logic on my part... can anyone help sharpen me up on this? Cheers...

推荐答案

我将创建一个数组,其中所有值都在[min,max]范围内,然后与所有现有范围相交:

I'd create an array with all the values in the [min,max] range, then do an intersect with all the existing ranges:

$new_range = range($min, $max);
foreach ($current_ranges as $range) {
  if (count(array_intersect($new_range, range($range["min"], $range["max"])))) {
    throw new RangeException();
  }
}

这将在与新范围一致的第一个现有范围内引发异常.

This will throw an exception on the first already-existing range coinciding with the new one.

这篇关于确保范围值不与现有范围重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆