-
Notifications
You must be signed in to change notification settings - Fork 0
/
challenge1.php
117 lines (88 loc) · 2.7 KB
/
challenge1.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/*
Challenge 1
Leverage the Random User Generator API (https://randomuser.me) to create user data which you will sort and store into separate files.
Specifications
Please commit your answer to a GitHub repository.
Retrieve data for 100 random users from only the United States and Germany, and the United Kingdom.
Your code should retrieve this data from a single API request. The response format should be in JSON.
Output the response into a file that should be committed with the rest of your code.
Using January 1, 1990 as a midpoint, divide and sort the 100 responses into two csv files based on the users’ birthdates.
Create one CSV file that contains all American males born after January 1, 1980.
The output csv files should have descriptive file names and contain column headers.
*/
error_reporting(E_ALL | E_STRICT);
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client;
// Create a client
$client = new GuzzleHttp\Client();
// Send a GET request to API
$response = $client->request('GET', 'https://randomuser.me/api', [
'query' => [
'results' => '100',
'nat' => 'us,de,gb'
]
]);
// stop here if invalid response
if ($response->getStatusCode() != 200) exit();
// decode response to array
$data = json_decode($response->getBody(), true);
$users = $data['results'];
// directory to store data
$dir = 'data';
if (! is_dir($dir)) {
mkdir($dir);
}
// open file pointers
$fp1 = fopen($dir . '/users_dob_before_010190.csv', 'w');
$fp2 = fopen($dir . '/users_dob_after_010190.csv', 'w');
$fp3 = fopen($dir . '/users_us_male_dob_after_010180.csv', 'w');
// build header
$csv_header = [];
foreach($users[0] as $k => $v) {
if (is_array($v)) {
foreach($v as $k2 => $v2) {
$csv_header[] = $k . '_' . $k2;
}
} else {
$csv_header[] = $k;
}
}
fputcsv($fp1, $csv_header);
fputcsv($fp2, $csv_header);
fputcsv($fp3, $csv_header);
// set variables
$midpoint1 = new DateTime('1990-01-01');
$midpoint2 = new DateTime('1980-01-01');
// parse data
foreach ($users as $user) {
// flatten user data
$row = [];
foreach($user as $v) {
if (is_array($v)) {
foreach ($v as $v2) {
$row[] = $v2;
}
} else {
$row[] = $v;
}
}
// dob object
$dob = new DateTime($user['dob']);
// write csv based on midpoint1
if($dob >= $midpoint1) {
fputcsv($fp2, $row);
} else {
fputcsv($fp1, $row);
}
// write csv based on midpoint2
if($dob >= $midpoint2) {
if($user['gender'] == 'male' && $user['nat'] == 'US') {
fputcsv($fp3, $row);
}
}
}
// close fp
fclose($fp1);
fclose($fp2);
fclose($fp3);