1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
$arbre = array (
'id' => 2,
'children' =>
array (
0 =>
array (
'id' => 3,
'children' =>
array (
),
),
1 =>
array (
'id' => 8,
'children' =>
array (
),
),
2 =>
array (
'id' => 9,
'children' =>
array (
0 =>
array (
'id' => 50,
'children' =>
array (
),
),
),
),
),
);
aff(cherche(8, $arbre));
aff(cherche(9, $arbre));
aff(cherche(50, $arbre));
aff(cherche(51, $arbre));
function cherche($aiguille, $arbre, $chemin_trouve = [])
{
$chemin_trouve[] = $arbre["id"];
if ($aiguille === $arbre["id"]) {
return $chemin_trouve;
}
if (count($arbre["children"]) > 0) {
foreach ($arbre["children"] as $enfant) {
$reponse = cherche($aiguille, $enfant, $chemin_trouve);
if (count($reponse) > 0) {
return $reponse;
}
}
}
// pas trouvé, retourne un tableau vide
return [];
}
function aff($var)
{
echo "<pre>";
echo htmlspecialchars(var_export($var, TRUE));
echo "</pre>";
} |
Partager