2013-06-12 30 views
-1

我有一個ID字段和一個引用另一個元組的ID的數據庫。檢查一個數組的元素,看看n-1值是否在數據庫中作爲參考

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) = 6ref(6)=4ref(4)=1

+0

你有沒有嘗試過我們可以看到的東西? – Toto

+0

你還需要檢查循環引用,否則你創建一個無限循環:) - 但我可以告訴你答案:它通過編程它的作品。你到目前爲止嘗試了什麼?你跑哪個問題? – hakre

回答

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:我很少用做,而不是一段時間,但我相信這是需要的,所以你可以隨時運行第一次檢查。這個函數不會驗證你的數組是否至少有2個條目是該功能的要求,因此請添加該簽入。

相關問題