-1

我有一个带有 ID 字段的数据库和一个引用字段,该字段引用另一个具有 id 的元组。

table  
id | ref   
1  | null
2  | null
3  | 1
4  | 1
5  | 1
6  | 4
7  | 6

我想验证给定数组以查看每个元素是否具有 n-1 个元素值作为参考。如果链在某处损坏....数组不验证。

例如:验证array(1,4,6,7)whileref(7) = 6ref(6)=4ref(4)=1

4

1 回答 1

1
$source = [1 => null, 2 => null, 3 => 1, 4 => 1, 5 => 1, 6 => 4, 7 => 6];

$a = [1, 4, 6, 7];
$b = [1, 2, 3];

function validate($source, $check) {
    $thisNum = array_shift($check);
    //This checks the first number, which must not have a ref, it will have NULL value in source array.
    if ($source[$thisNum] != NULL) {
        return false;
    }
    do {
        $nextNum = array_shift($check);
        //This checks that the next number in the list has the ref of the previous number in the source array
        if ($source[$nextNum] !== $thisNum) {
            return false;
        }
        //This is so the next check can use the current next num as the current num to check
        $thisNum = $nextNum;
    } while (count($check));
    //If we haven't failed yet, it must be good!
    return true;
}

var_dump(validate($source, $a));
var_dump(validate($source, $b));

结果是:

boolean true
boolean false

TBH:我几乎从不使用 do-while 代替 while,但我相信这里需要它,所以你总是可以运行第一次检查。此函数不会验证您的数组是否至少有 2 个条目,这是该函数的要求,因此请添加该签入。

于 2013-06-12T07:38:09.930 回答