PHP getting values from nested json - php

I have this json listed below. I was using json_decode to get some of the values. Such as getting the id value:
$decoded_array = json_decode($result, true);
foreach($decoded_array['issue'] as $issues ){
$value[] = $issues["id"];
This method is working for getting the id value, however, I want to get the emailAddress values for both Bob and John. I believe you can get a single value by doing this:
$value[] = $issues["fields"][people][0][emailAddress];
Is it possible to get both email addresses in an efficient manner?
Edited --------
How would you get data with an expanded dataset? Example:
{
"startAt": 0,
"issue": [
{
"id": "51526",
"fields": {
"people": [
{
"name": "bob",
"emailAddress": "bob#gmail.com",
"displayName": "Bob Smith",
},
{
"name": "john",
"emailAddress": "john#gmail.com",
"displayName": "John Smith",
}
],
"skill": {
"name": "artist",
"id": "1"
}
}
},
{
"id": "2005",
"fields": {
"people": [
{
"name": "jake",
"emailAddress": "jake#gmail.com",
"displayName": "Jake Smith",
},
{
"name": "frank",
"emailAddress": "frank#gmail.com",
"displayName": "Frank Smith",
}
],
"skill": {
"name": "writer",
"id": "2"
}
}
}
]
}
I only want to extract the email addresses from both "fields". Is there an easy way to loop through all the "fields" to get "emailAddress" data?

You need to delve deeper into the array.
foreach ($decoded_array['issue'][0]['fields']['people'] as $person) {
echo $person['emailAddress'];
}

Related

Extract element from nested JSON

There is json response:
{
"id": "1234567890123456789",
"creation_date": 12345678,
"event": "WAITING_PAYMENT",
"version": "2.0.0",
"data": {
"product": {
"id": 213344,
"name": "Product Name",
"has_co_production": false
},
"affiliates": [
{
"name": "Affiliate name"
}
],
"buyer": {
"email": "buyer#email.com"
},
"producer": {
"name": "Producer Name"
},
"commissions": [
{
"value": 0.65,
"source": "MARKETPLACE"
},
{
"value": 3.10,
"source": "PRODUCER"
}
],
"purchase": {
"approved_date": 1231241434453,
"full_price": {
"value": 134.0
},
"original_offer_price": {
"currency_value": "EUR"
"value": 100.78,
},
"price": {
"value": 150.6
},
"order_date": "123243546",
"status": "STARTED",
"transaction": "HP02316330308193",
"payment": {
"billet_barcode": "03399.33335 33823.303087 198801027 2 876300015000",
"billet_url": "https://billet-link.com/bHP023163303193",
}
},
"subscription": {
"status": "ACTIVE",
"plan": {
"name": "plan name"
},
"subscriber": {
"code": "12133421"
}
}
}
}
My question is how to extract data["buyer"]["email"] in PHP ?
I only need to extract the email information from the buyer table inside the data table.
First, you need to decode the json to a PHP array (or an object), then you can access the requested information from the decoded data.
$data = json_decode('the json string most place here', true);
$email = $data['buyer']['email'];
Place your json string in the first argument of json_decode() function.

Combine $request->request and $request->files arrays

Im posting a multipart with text and files and trying to pass data to form, but these data are separated, so I want to combine them.
$request->request->all()
$request->files->all()
$form = $this->createForm(ParkingType::class, new Parking());
$form->submit($INeedToPassTheCombinedArray);
if ($form->isValid()) {
return $form->getData();
}
Both arrays have the same structure.
For example:
$request->request->all()
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [{
"total": 4,
"capacity": 928,
"places": [{
"total": 123,
"name": "test",
"address": "test"
},
{
"total": 123,
"name": "test",
"address": "test"
}
]
}]
}
$request->files->all()
{
"parkings": [{
"generalInfo": "File.pdf",
"places": [{
"logo": "File1.png"
},
{
"logo": "File2.png"
}
]
}]
}
I want to combine then in one single array, getting this:
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [{
"total": 4,
"capacity": 928,
"generalInfo": "File.pdf",
"places": [{
"total": 123,
"name": "test",
"address": "test",
"logo": "File1.png"
},
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File2.png"
}
]
}]
}
I tried using array_merge, but the result is a single array which contain 2 arrays. It is not adding the data of one array in the respective position of the other array.
I want to know if there is some method for do this automatically and elegant.
Hope this will solve your problem
$data1 = json_decode($data,true);// first post array
$data2 = json_decode($file,true);//second file array
foreach($data1['parkings'] as $key=>&$val){ // Loop though one array
$val2 = $data2['parkings'][$key]; // Get the values from the other array
$val += $val2; // combine 'em
foreach($val['places'] as $k=>&$v){
$val3 = $val2['places'][$k]; // Get the values from the other array
$v += $val3; // combine 'em
}
}
echo json_encode($data1);
{
"name": "Test",
"taxId": "asd12",
"nationality": "england",
"parkings": [
{
"total": 4,
"capacity": 928,
"places": [
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File1.png"
},
{
"total": 123,
"name": "test",
"address": "test",
"logo": "File2.png"
}
],
"generalInfo": "File.pdf"
}
]
}

How to group JsonArray result content in json index

In my JsonArray result, I want to put all the content in index [{'data':{contenthere}}]
Here is my code :
$data = [];
$gr = []; //some data here
foreach($gr as $g) {
$data[] = [
'id' => $g['id'],
'name' => $g['name'],
'phone' => $g['pĥone']
]
}
return $data;
return $data output :
string(249) "[
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
},
]
cool, now I want to put all this in ['data'] so the result needed :
string(249) "[
{
"data": {
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
},
}
}
]
As Google JSON Style
I tried the $data[]['data'] but the "data": repeats in each object
foreach($gr as $g) {
$data[]['data'] = ...
I thought do do group_by function but I think that there is a simple solution for that
I'm not sure if you really need the extra array at the top level, but use...
return [["data" => $data]];
should give you the result.
Use json_encode to achieve this:
$json = json_encode(array('data' => $data));
print_r($json);
Result:
{
"data": [
{
"id": "112",
"name": "john",
"phone": "XXXXXXXXX"
},
{
"id": "213",
"name": "mike",
"phone": "XXXXXXXXX"
},
{
"id": "246",
"name": "jess",
"phone": "XXXXXXXXX"
}
]
}

parse extended json output file from cucumber with php

i am tring to parse a special json content. I got this as an output file from a cucumber execution. The goal is it to decode some values like the name the status and some other content. How can i encode that.
Another concern would be a transformation of json into a CSV.
It is not important for me to use php. Java or Perl would be an alternative.
This file I am gonna call in php with:
$jsonconntent = file_get_contents("/home/xxx/test1.json");
The json conten looks like this (I posted only the beginning):
[
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
"type": "scenario",
"before": [
{
"output": [
"Default Timestamp start: 1516024716000"
],
"match": {
"location": "features/support/env.rb:32"
},
"result": {
"status": "passed",
"duration": 191690
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:13"
},
"result": {
"status": "passed",
"duration": 52117
}
},
{
"match": {
"location": "capybara-2.17.0/lib/capybara/cucumber.rb:21"
},
"result": {
"status": "passed",
"duration": 25885
}
}
],
"steps": [
{
"keyword": "Given ",
"name": "a Android A-Party",
"line": 4,
"output": [
"Got handset with number unvisable, IMSI: notfor, android-Id: yourfone, VNC: 11111, port: 9981"
],
"match": {
"location": "features/step_definitions/idrp_steps.rb:11"
},
"result": {
"status": "passed",
"duration": 1415024760
},
"after": [
{
"match": {
"location": "features/support/env.rb:24"
},
"result": {
"status": "passed",
"duration": 264339
}
}
]
}
Use:
$data = json_decode($jsonconntent, true);
You will have the data with javascript objects as arrays, not PHP objects.
To save it as CSV, it depends on the structure of the data. In this case, it is complicated:
{
"uri": "features/complete_ski.feature",
"id": "complete_ski_with_time",
"keyword": "Feature",
"name": "Complete_Ski_with_time",
"description": "",
"line": 1,
"elements": [
{
"id": "complete_ski_with_time;time_part_preamble",
"keyword": "Scenario",
"name": "time_part_preamble",
"description": "",
"line": 3,
...
How do you put the data in the column elements? Data is so nested that it cannot be transformed into a tabular format with column headers and one value per column in each row.
As to how to access the data, you can do this:
$first_element_id = $data[0]['elements'][0]['id'];
foreach ( $data as $item ) {
$uri = $item['uri'];
foreach ( $item['elements'] as $element ) {
$name = $element['name'];
}
}
As asked in one of the comments, this is how to access the 'Default Timestamp start':
foreach ($data as $item) {
foreach ($item['elements'] as $element) {
foreach ($element['before'] as $before) {
if (isset($before['output'])) {
foreach ($before['output'] as $output) {
echo sprintf("%s\n", $output);
}
}
}
}
}

Parsing a JSON file with multiple levels in a MySQL database

I've some trouble with parsing a JSON file into a MySQL database. It's an export of some Facebookstats.
Because I've multiple export of multiple pages, it's important that I've the corresponding ID in the database.
The JSONfile (or cURL from Facebook) looks like this:
{
"data": [
{
"name": "impressions",
"period": "week",
"values": [
{
"value": 123456789,
"end_time": "2016-01-01T08:00:00+0000"
},
{
"value": 12345678,
"end_time": "2016-01-02T08:00:00+0000"
},
{
"value": 1234567,
"end_time": "2016-01-03T08:00:00+0000"
},
{
"value": 123456,
"end_time": "2016-01-04T08:00:00+0000"
},
{
"value": 12345,
"end_time": "2016-01-05T08:00:00+0000"
}
],
"title": "Weekly Impressions",
"description": "The number of impressions seen of any content associated with your Page. (Total Count)",
"id": "101010101010\/insights\/page_impressions\/week"
}
],
"paging": {
"previous": "1",
"next": "2"
}
}
I would, ideally, parse this data into a MySQL database that looks like this:
id value end_time
101010101010 123456789 2016-01-01T08:00:00+0000
101010101010 12345678 2016-01-02T08:00:00+0000
101010101010 1234567 2016-01-03T08:00:00+0000
101010101010 123456 2016-01-04T08:00:00+0000
101010101010 12345 2016-01-05T08:00:00+0000
I hope someone had some ideas :-)
Use json_decode(). Example:
$jsonString = '{
"data": [
{
"name": "impressions",
"period": "week",
"values": [
{
"value": 123456789,
"end_time": "2016-01-01T08:00:00+0000"
},
{
"value": 12345678,
"end_time": "2016-01-02T08:00:00+0000"
},
{
"value": 1234567,
"end_time": "2016-01-03T08:00:00+0000"
},
{
"value": 123456,
"end_time": "2016-01-04T08:00:00+0000"
},
{
"value": 12345,
"end_time": "2016-01-05T08:00:00+0000"
}
],
"title": "Weekly Impressions",
"description": "The number of impressions seen of any content associated with your Page. (Total Count)",
"id": "101010101010\/insights\/page_impressions\/week"
}
],
"paging": {
"previous": "1",
"next": "2"
}
}';
Then decode it to an associative array:
$assocData = json_decode($jsonString, true); //Setting second optional parameter to true makes it return an associative array.
Then access it however you want:
$data = $assocData['data'];

Categories