I'm trying to retrieve data from an API that gives a response like so:
{
"data":[
{
"first_name":"John",
"last_name":"Smith",
"group":"3",
"email":"jsmith#talktalk.net"
},
{
"first_name":"John",
"last_name":"Doe",
"group":"3",
"email":"johndoe#aol.com"
}
],
"meta":{
"pagination":{
"total":2,
"count":2,
"per_page":500,
"current_page":1,
"total_pages":1,
"links":[
]
}
}
}
I'm trying to use Guzzle to import into my Laravel app
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'http://localhost/members.json');
$data = (string) $response->getBody();
and then a foreach to loop over each record and then add it to the database. Right now though I'm struggling to drill down into a record.
What am I missing?
EDIT: Here's the foreach
foreach ($data['data'] as $person) {
Contact::create(array(
'name' => $person->first_name,
));
}
Your $data variable holds json. Lets first make it a nice array and then loop it through
$response = json_decode($data, true);
Now the loop itself:
foreach($response['data'] as $element) {
$firstName = $element['first_name'];
$lastName = $element['last_name'];
$group = $element['group'];
$email = $element['email'];
//Now here you can send it to the modele and create your db row.
}
Related
I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I'm getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php
$idtemp = extractfiles($fol_id, $email);
foreach ($idtemp['items'] as $val) {
$id = $val['id'];
$val = array(
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
);
$enc = json_encode($val);
$val = '{"files":['.$enc.']}';
echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
You should no do $val = '{"files":['.$enc.']}';
Use json_encode to make json, don't do it manual
Create an object with desired keys outside the loop
Push anything to the desired array
Convert to json
<?php
$idtemp = extractfiles($fol_id, $email);
$json = (object) [
"files" => []
];
foreach ($idtemp['items'] as $val) {
$json->files[] = (object) [
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
];
}
$json = json_encode($json);
echo($json);
If I use some dummy values to create an example, the output is:
{
"files": [
{
"webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk\""
}
]
}
As you can test in this online demo
I'm processed some JSON data that is sent via HTTP POST to my PHP file. I then need to extract some elements and create a PHP array containing these, so I can then loop through this array and perform some actions.
Here's a sample of how the JSON data that is sent looks:
[
{
"fileName": "Invoices",
"event": "processed",
"serverName": "server1.acme.com",
"timestamp": 1574229999
},
{
"fileName": "Invoices",
"event": "processed",
"serverName": "server2.acme.com",
"timestamp": 1574228341
},
{
"fileName": "Payments",
"event": "processed",
"hostname": "server3.acme.com",
"timestamp": 1574766997
}
]
I'm then decoding this to parse out just the elements I need:
$payload = #file_get_contents('php://input');
$records= json_decode( $payload, FALSE );
$sessionsArray = array();
foreach($records as $record){
$hostname = $record->hostname;
$fileName = $record->fileName;
// need to add these to the $sessionsArray for each iteration of the loop
}
I would like to create a new array $sessionsArray and add the $hostname and $fileName variables to this for each iteration in the foreach loop. I then intend to do another foreach on the $sessionsArray and perform some actions using the $hostname and $fileName for each element of the array.
I'm stuck on how to add the variables within the first foreach loop to the $sessionsArray array so I can then subsequently loop through that array.
foreach($records as $record){
$sessionsArray[] = [
'hostname' => $record->hostname,
'fileName' => $record->fileName,
];
}
And then you can do:
foreach($sessionsArray as $entry){
$hostname = $entry['hostname'];
$fileName = $entry['fileName'];
}
=== OR ===
foreach($records as $record){
$sessionsArray[$record->hostname] = $record->fileName;
}
and then you can do:
foreach($sessionsArray as $hostname => $fileName){
// $hostname contains the hostname
// $filename contains filename
}
Just FYI, based on the JSON object you provided your code SHOULD be:
$hostname = $record->serverName;
$fileName = $record->fileName;
$sessionsArray = array();
foreach($records as $key => $record){
$sessionsArray[$key]['hostname'] = $record->hostname;
$sessionsArray[$key]['fileName'] = $record->fileName;
}
You need to get the last key of sessionsArray before every loop and pass that last key while adding to variable.
Here is example:
$sessionsArray = !empty($sessionsArray)?$sessionsArray:[];
$continueKey = (#array_pop(array_keys($sessionsArray)))?#array_pop(array_keys($sessionsArray))+1:0;
foreach($records as $record){
$sessionsArray[$continueKey]['hostname'] = $record->hostname;
$sessionsArray[$continueKey]['fileName'] = $record->fileName;
}
So from a Get request I get back a response in this structure:
{
"chromeosdevices" : [
{
"somekey" : "somevalue",
"annotatedUser" : "annotatedUserValue",
"activeTimeRanges" : [
{
"date" : "dateValue",
"activeTime" : "activeTimeValue"
}
],
"somekey" : "somevalue",
},
]
}
How can I access both DateValue and ActiveTimeValue?
I have tried it with this code:
$dec = json_decode($response);
$filteredResults= array();
if (! empty($dec->chromeosdevices)) {
foreach ($dec->chromeosdevices as $chromeosdevice) {
$user['annotatedUser'] = $chromeosdevice->annotatedUser;
$user['activeTimeRanges_date'] = $chromeosdevice->activeTimeRanges->date;
$user['activeTimeRanges_activeTime'] = $chromeosdevice->activeTimeRanges -> activeTime;
$filteredResults[] = $user;
}
}
echo '<pre>';print_r($filteredResults);echo '</pre>';
However, I only get back the annotatedUser, but not the date and active time. Why is that?
As it is another object in an array use $chromeosdevice->activeTimeRanges[0]->date;
That is in an array so maybe another loop would be the safest way to deal with this
$dec = json_decode($response);
$filteredResults= array();
if (! empty($dec->chromeosdevices)) {
foreach ($dec->chromeosdevices as $chromeosdevice) {
$user = []; // init and remove last loops info
$user['annotatedUser'] = $chromeosdevice->annotatedUser;
foreach ($chromeosdevice->activeTimeRanges as $tr) {
$user['activeTimeRanges_date'][] = $tr->date;
$user['activeTimeRanges_activeTime'][] = $tr->activeTime;
}
$filteredResults[] = $user;
}
}
echo '<pre>';print_r($filteredResults);echo '</pre>';
I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);
I have a json file and I want to display it data using PHP. My below code gives me error,
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$users = $data['devices'];
foreach($users as $user)
{
echo $user['id'];
echo $user['user'];
}
When I replace the 3rd LOC with $users = $data['user']; then it display some data with single alphabet i don't know in which order.
Data.json file contains the following data
{
"user":
{
"id":"#03B7F72C1A522631",
"user":"test#mail.com",
"password":"123",
"email":"test#mail.com",
"name":"m",
"creationDate":1385048478,
"compression":true,
"imageProfile":"medium",
"videoProfile":"medium",
"blockAdvert":true,
"blockTracking":true,
"devices":[
{
"id":"#13C73379A7CC2310",
"udid":"cGMtd2luNi4xLV",
"user":"test#mail.com",
"creationDate":1385048478,
"status":"active",
},
{
"id":"#FE729556EDD9910D",
"udid":"C1N1",
"user":"test#mail.com",
"creationDate":1385291938,
"status":"active",
}]
},
"status":
{
"version":"0.9.5.0",
"command":"getuser",
"opf":"json",
"error":false,
"code":0
}
}
I believe you skipped 1 node, try:
$users = $data['user']['devices'];
This should work;
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$users = $data['user']['devices'];
foreach($users as $user) {
echo $user['id'];
echo $user['user'];
}
There is one key before 'devices'.
I think you may want do display all the devices info, you can change you code to:
$json = file_get_contents('data.json');
$data = json_decode($json,true);
// change the variable name to devices which is clearer.
$devices = $data['user']['devices'];
foreach ($devices as $device)
{
echo $device['id'];
echo $device['user'];
}
You are not accessing your json correctly. You need to access it like this.
$yourVariable = $data['users']['devices'];
Try that.