-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompany_data.php
74 lines (62 loc) · 1.93 KB
/
company_data.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
<?php
class Travel
{
public static function fetchData($url)
{
$json = file_get_contents($url);
return json_decode($json, true);
}
}
class Company
{
private $companies;
private $travels;
public function __construct($companies, $travels)
{
$this->companies = $companies;
$this->travels = $travels;
}
public function buildCompanyTree($parentId = "0")
{
$tree = [];
foreach ($this->companies as &$company) {
if ($company['parentId'] == $parentId) {
$company['children'] = $this->buildCompanyTree($company['id']);
$tree[] = $company;
}
}
return $tree;
}
public function calculateTravelCost(&$companies)
{
$totalCost = 0;
foreach ($companies as &$company) {
$companyCost = 0;
foreach ($this->travels as $travel) {
if ($travel['companyId'] == $company['id']) {
$companyCost += $travel['price'];
}
}
$company['cost'] = $companyCost + $this->calculateTravelCost($company['children']);
$totalCost += $company['cost'];
}
return $totalCost;
}
}
class TestScript
{
public function execute()
{
$start = microtime(true);
$companiesUrl = 'https://5f27781bf5d27e001612e057.mockapi.io/webprovise/companies';
$travelsUrl = 'https://5f27781bf5d27e001612e057.mockapi.io/webprovise/travels';
$companiesData = Travel::fetchData($companiesUrl);
$travelsData = Travel::fetchData($travelsUrl);
$companyObj = new Company($companiesData, $travelsData);
$companyTree = $companyObj->buildCompanyTree();
$companyObj->calculateTravelCost($companyTree);
echo json_encode($companyTree, JSON_PRETTY_PRINT);
echo 'Total time: '. (microtime(true) - $start);
}
}
(new TestScript())->execute();