빌드 기능을 실행하는 동안 이미 해시로 결과를 생성 한 모든 구성 요소를 추적하고, 그 중 하나가 다시 발생하면 무시합니다.
// Sample "database":
$components = array(
1 => array (
"id" => 1,
"name" => "bike",
"needs" => array (
array ("id" => 2, "count" => 2), // 2 wheels
array ("id" => 3, "count" => 1), // 1 handlebar
),
"folder" => "/my/folders/bike"
),
2 => array(
"id" => 2,
"name" => "weel",
"needs" => array(
array("id" => 4, "count" => 1), // 1 tire
array("id" => 1, "count" => 1) // 1 wheel?? - erroneous information!
),
"folder" => "/my/folders/wheel"
),
3 => array(
"id" => 3,
"name" => "handlebar",
"needs" => array(),
"folder" => "/my/folders/handlebar"
),
4 => array(
"id" => 4,
"name" => "tire",
"needs" => array(),
"folder" => "/my/folders/tire"
)
);
// Build function: returns a list of folders related
// to all the parts of the given component.
function build($componentId, $components, $hash = array()) {
// Protection against infinite recursion:
if (isset($hash[$componentId])) return [];
$elem = $components[$componentId];
// set hash, keyed by component ID.
$hash[$componentId] = 1;
// Add folder for this component
$folders[] = $elem['folder'];
// Collect folders of dependent components recursively
foreach($elem['needs'] as $child) {
// ... pass the hash as third argument
$folders = array_merge($folders, build($child["id"], $components, $hash));
}
return $folders;
}
// Example call: build component with ID 1, returning a list of folders:
print_r (build(1, $components));
위의 코드의 출력은 다음과 같습니다 : 여기
일부 상용구 당신이 영감을 사용할 수있는 코드입니다 그래서
Array
(
[0] => /my/folders/bike
[1] => /my/folders/wheel
[2] => /my/folders/tire
[3] => /my/folders/handlebar
)
자전거가 두 번 발생했습니다, 그것은이었다 그냥 무시.
왜 자전거에 자전거가 필요합니까? 휠은 더 많은 제품, 자전거, 자동차, 스케이트, 스케이트 보드에 사용될 수있는 부품입니다. 자전거는 자체적으로 존재할 수 있지만 자전거는 없습니다. – KhorneHoly
다소 관련이있는 것으로 밝혀졌습니다 : [여기] (http://codereview.stackexchange.com/questions/94669/adjacency-list-with-array-data), 부모는 자전거와 휠로 간주합니다. – Viral
나는 미래에 내 데이터베이스에 수천 개의 기사가있을 것이며 쉽게 실수를 할 수 있다고 가정합니다. 그것이 나에게 달린 것이지만 나는 신경 쓰지 않을 것입니다 ... 나는 관심있는 사람들을 위해 일합니다 ... 아 – void