我有一个带有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)
,ref(7) = 6
,ref(6)=4
和ref(4)=1
答案 0 :(得分: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个条目是函数的要求,因此请添加该函数。