It’s a good idea, but relies upon immediate referral.
For non-immediate referral…
You’re going to have to tree the data from the table, as Drummin has done, but then you’ll need to recursively define a function to crawl down the tree.
Something like…
function treedrill(startnode) {
$toprank = startnode.rank;
foreach(startnode.children AS child) {
$toprank = max($toprank,treedrill(child));
}
return $toprank
}
while($X != 0) {
foreach(X.children AS child) {
$legs[treedrill(child)]++;
}
Note that we dont care what the makeup of the tree is; we only care what the top rank of the leg is, since multiple people in the same leg dont count, and someone of a higher rank counts as all lower ranks.
Then, do a comparison:
$rank = 1; //Assumed shortcutting somewhere if TM conditions not met
for(i = 1; i < MaxRank#; i++) {
if(array_sum(array_slice($legs,TargetRank)) > TargetNumber) { $rank = TargetRank; } else { break; }
}
X = x.parent;
}
or something of the like.
(Note: If you want to try getting fancy and storing the result of person X for person X’s parent to avoid re-counting, you could. Slice the key of the highest value of $legs, and feed it back as $legs for the next loop, with a way to tell your function to ignore a child if child = X.)