-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq3.php
More file actions
93 lines (75 loc) · 2.43 KB
/
q3.php
File metadata and controls
93 lines (75 loc) · 2.43 KB
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
84
85
86
87
88
89
90
91
92
93
<?php
/**
## Question 3 - Hierarchies
I would like you to implement a solution that prints out hierarchies, based on the data below (these could be navigation trees).
You have the following array:
```php
$locations = array(
3 => array("Building1", 2),
2 => array("Area1", 1),
0 => array("Floor1", 3),
1 => array("City1"),
4 => array("Room1", 0),
13 => array("Building2", 12),
12 => array("Area2", 11),
14 => array("Room2", 10),
10 => array("Floor2", 13),
11 => array("City2")
);
```
The structure of the array is as follows:
```
key => array(term, parent_id)
```
In each element of the array, the second value points to the parent of the element itself. So for instance in the first array, ```City1``` is the root element and ```Area1``` is the first child, because the second element of ```Area1``` is ```1```, which is the ```key``` of ```City1```.
The expected output is:
```
City1 > Area1 > Building1 > Floor1 > Room1
City2 > Area2 > Building2 > Floor2 > Room2
```
**Tip**. Think abstract and think about recursion.
**Plus points**. Write this as an Object Oriented Class
*/
class LocationHierarchy {
private array $locations;
public function __construct(array $locations)
{
$this->locations = $locations;
}
private function printHierarchy(int $id, string $prefix = "") : string
{
// Search for $key in $location[1] of list
foreach ($this->locations as $key => $location) {
if (!isset($location[1])) {
continue;
}
if ($location[1] !== $id) {
continue;
}
$prefix .= " > " . $location[0] . $this->printHierarchy($key);
}
return $prefix;
}
public function printAllHierarchies()
{
foreach ($this->locations as $id => $location) {
if (!isset($location[1])) {
echo $this->printHierarchy($id, $location[0]);
echo PHP_EOL;
}
}
}
}
$locations = array(
3 => array("Building1", 2),
2 => array("Area1", 1),
0 => array("Floor1", 3),
1 => array("City1"),
4 => array("Room1", 0),
13 => array("Building2", 12),
12 => array("Area2", 11),
14 => array("Room2", 10),
10 => array("Floor2", 13),
11 => array("City2")
);
$hierarchy = (new LocationHierarchy($locations))->printAllHierarchies();