-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecursive_examples.php
83 lines (73 loc) · 1.49 KB
/
recursive_examples.php
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
82
83
<?php
// recursive example 1
$categories = [
[
"id" => 1,
"parent" => 0,
"name" => "categori 1"
],
[
"id" => 2,
"parent" => 0,
"name" => "categori 2"
],
[
"id" => 3,
"parent" => 0,
"name" => "categori 3"
],
[
"id" => 4,
"parent" => 1,
"name" => "categori 4"
],
[
"id" => 5,
"parent" => 2,
"name" => "categori 5"
]
];
function listCategories($categories, $parent = 0)
{
$html = "";
foreach ($categories as $categori) {
$html .= "<ul>";
if ($categori["parent"] == $parent) {
$html .= "<li>" . $categori["name"];
$html .= listCategories($categories, $categori["id"]);
$html .= "</li>";
}
$html .= "</ul>";
}
return $html;
}
echo listCategories($categories);
// recursive example 2
$arr = [
"name" => "Furkan",
"surname" => "Aygur",
"sports" => [
"swimming" => "true",
"bodybuilding" => "true",
"defense_sports" => [
"judo" => "false",
"capoira" => "false",
]
]
];
function getInfo($arr, $keys)
{
foreach ($arr as $key => $value) {
if ($key == $keys) {
return $value;
}
if (is_array($value)) {
$result = getInfo($value, $keys);
if ($result) {
return $result;
}
}
}
}
echo getInfo($arr, "swimming");
?>