Skip to content

Instantly share code, notes, and snippets.

@wesscoby
Last active April 13, 2019 19:50
Show Gist options
  • Save wesscoby/c807dc73cde13d4093934b4eb38147b2 to your computer and use it in GitHub Desktop.
Save wesscoby/c807dc73cde13d4093934b4eb38147b2 to your computer and use it in GitHub Desktop.
<?php
$people = '{
"data":[{
"first_name":"jake",
"last_name":"bennett",
"age":31,
"email":"[email protected]",
"secret":"VXNlIHRoaXMgc2VjcmV0IHBocmFzZSBzb21ld2hlcmUgaW4geW91ciBjb2RlJ3MgY29tbWVudHM="
},{
"first_name":"jordon",
"last_name":"brill",
"age":85,
"email": "[email protected]",
"secret":"YWxidXF1ZXJxdWUuIHNub3JrZWwu"
},]}';
/**
* Instructions:
*
* Given the above JSON, build a simple PHP script to import it.
*
* Your script should create two variables:
*
* - a comma-separated list of email addresses
* - the original data, sorted by age descending, with a new field on each record
* called "name" which is the first and last name joined.
*/
// Solution
// removing the trailing comma
$people = preg_replace("/(,])/", "]", $people);
//decoding the json object into a php object
$decoded_object = json_decode($people, false);
// the two variables to hold the output
$email_addresses = [];
$new_people_record = [];
// using the loop to populate both variables
foreach ($decoded_object->data as $data_item) {
array_push($email_addresses, $data_item->email);
array_push($new_people_record,
[
"name" => "$data_item->first_name $data_item->last_name",
"first_name" => $data_item->first_name,
"last_name" => $data_item->last_name,
"age" => $data_item->age,
"email" => $data_item->email,
"secret" => $data_item->secret
]
);
}
// Sorting age by descending order
usort($new_people_record, function ($a, $b) { return $b['age'] - $a['age']; });
// comma-separated email list
$email_addresses = implode(', ', $email_addresses);
// output
echo '<pre>';
echo $email_addresses . '<br>';
print_r($new_people_record);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment