干得好!:
<?php
// dataset
$clientset = array(
array(1013, 1154),
array(1013, 1322),
array(1154, 1525),
array(1525, 1526)
);
$children = array();
// make an array with children to see which nodes have none
foreach($clientset as $set) {
if(!isset($children[$set[0]])) $children[$set[0]] = array($set[1]);
else $children[$set[0]][] = $set[1];
}
// array with parents
$parents = array();
foreach($clientset as $set) {
$parents[$set[1]] = $set[0];
}
// for each node with no children, begin the search!
foreach($clientset as $set) {
if(!isset($children[$set[1]])) {
echo getPath($set[1]).'</br>';
}
}
// recursively search to parents and print them
function getPath($child) {
global $parents;
if($parents[$child]) {
return (getPath($parents[$child]).' => '.$child);
} else return $child;
}
?>
这输出:
1013 => 1322
1013 => 1154 => 1525 => 1526
这个想法是查看哪些节点没有子节点。然后,遍历他们的父母。您可能不需要像现在这样的输出,但我相信您可以通过这种方式解决它。享受!