Related
Sorry for the confusing title. I am having a bit of an issue here merging some JSON files. I need to merge all the products into one array in a separate file.
I have a directory full of same structured json files. I am using glob to select all files and decode->append-->encode json files into one large file.
Here is my code:
<?php
$files = glob("*.json");
$newDataArray = [];
foreach($files as $file){
$thisData = file_get_contents($file);
$thisDataArray = json_decode($thisData);
$newDataArray[] = $thisDataArray;
}
$newDataJSON = json_encode($newDataArray);
file_put_contents("merged.json",$newDataJSON);
?>
Now, the above code seems to work great but I only want to extract all the products.
Quick example of what I need to achieve.
File1.json
{
"status": true,
"user": {
"username": "sally",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "35vR4hr",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "na1Id4t",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
File2.json
{
"status": true,
"user": {
"username": "Jessica",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "wjiefi94",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
I want the data to be merged like:
merged.json
{
"products": [
{
"id": "wjiefi94",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
I hope this makes sense. I feel like I have hit a dead end here. Any help is greatly appreciated.
would it be possible for you to call an external tool like "jq"? handling json (just like csv), especially with many files, is not something you should be doing manually.
btw, your example does not have commas between products 2 and 3 and 3 and 4.
Your new code on line 5 should probably read like this with the array brackets? Otherwise you are overwriting the contents of the last files:
$thisDataArray[] = json_decode($thisData);
And why are you merging products from Sally and Jessica into the same user? Maybe you can just extract all the products objects into one file?
More of a code review than an answer, hope it helps ;)
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'];
I've tried to switch the datasource of the Kendo UI Gantt example inside PHP. I have mapped the schema with what is being returned, but I just get a blank gantt chart with one heading - "undefined".
{
"1": {
"id": "1",
"orderId": "1",
"title": "TESTER1",
"start": "\/new Date('2016-01-01 09:00:00')\/",
"end": "\/new Date('2016-02-01 00:00:00')\/",
"project": "1",
"client": "4218",
"parent": "0",
"percentComplete": "10.11"
},
"2": {
"id": "2",
"orderId": "2",
"title": "TESTER2",
"start": "\/new Date('2016-01-03 09:00:00')\/",
"end": "\/new Date('2016-02-01 00:00:00')\/",
"project": "1",
"client": "4218",
"parent": "0",
"percentComplete": "50.00"
}
}
Above is the JSON being sent back to Kendo, but it doesn't render.
Found the solution:
I type casted the integers, set parents to null rather than zero (0) and converted dates into milliseconds in the PHP layer before putting through to Kendo. I also removed the keys which resulted in the below JSON to be created. This solved my rendering problem.
[{
"id": 1,
"orderId": 1,
"title": "TESTER1",
"start": "\/Date(1463126400000)\/",
"end": "\/Date(1463958000000)\/",
"project": 1,
"client": 4218,
"parent": null,
"percentComplete": 10
}, {
"id": 2,
"orderId": 2,
"title": "TESTER2",
"start": "\/Date(1463990400000)\/",
"end": "\/Date(1464130800000)\/",
"project": 1,
"client": 4218,
"parent": null,
"percentComplete": 50
}]
Been struggling with this for too long now, so am kindly asking for your help.
How can I, using PHP, get the values of the text fields in the reviews of which there are three in this JSON file below.
Want to use a foreach loop for this, thanks for helping me out!
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
],
You can use this code
<?php
$json = <<<EOF
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
]
}
EOF;
$array = json_decode($json, true);
$texts = array_map(
function($item) {
return $item['text'];
}, $array['reviews']
);
It doesn't seem like you need a foreach to fetch the reviews element. Not sure if I understood your question correct, but did you want something like this:
$assoc_json = json_decode($your_json, true);
var_dump($assoc_json['reviews']);
The above turns your json into an associative array, and just access the review element.
A simple, naive approach would be:
//Loads your json file 'tripadvisor' into jsonString
$jsonString = file_get_contents("/tripadvisor.json");
//Turns your string into an associative array
$tripJsonAssoc = json_decode($jsonString, true);
//Iterate through each review and store it in result
$result = array();
foreach($tripJsonAssoc['reviews'] as $review) {
$result[] = array('text' => $review['text'],
'rating' => $review['rating']);
}
//Do what you need to do with result
//...
Or you can just do your own stuff inside the foreach loop.
This answer gives you another way (more elegant) to create the 'result' array, but since you asked for a 'foreach', I thought I would add my 5 cents.
I am trying to extract a segment from the json file of Rome2Rio API with PHP but I cant get an output.
The json file from rome2rio:
{
"serveTime": 1,
"places": [
{ "kind": "town", "name": "Kozani", "longName": "Kozani, Greece", "pos": "40.29892,21.7972", "countryCode": "GR", "regionCode": "ESYE13" },
{ "kind": "city", "name": "Thessaloniki", "longName": "Thessaloniki, Greece", "pos": "40.64032,22.93527", "countryCode": "GR", "regionCode": "ESYE12" }
],
"airports": [],
"airlines": [],
"aircrafts": [],
"agencies": [{
"code": "KTEL",
"name": "KTEL",
"url": "http://www.ktelbus.com/?module=default\u0026pages_id=15\u0026lang=en",
"iconPath": "/logos/Trains/KTELgr.png",
"iconSize": "27,23",
"iconOffset": "0,0"
}
],
"routes": [
{ "name": "Bus", "distance": 121.04, "duration": 120, "totalTransferDuration": 0, "indicativePrice": { "price": 9, "currency": "EUR", "isFreeTransfer": 0 },
"stops": [
{ "name": "Kozani", "pos": "40.30032,21.79763", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" },
{ "name": "Thessaloniki", "pos": "40.6545,22.90233", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" }
]
The PHP code I wrote is:
$json_rome2rio = file_get_contents("http://free.rome2rio.com/api/1.2/json/Search?key=&oName=kozani&dName=thessaloniki");
$parsed_json_r = json_decode($json_rome2rio);
echo $parsed_json_r->agencies->name;
The agencies property contains an array of agencies (note the square brackets). To access the name as you're after, you can do the following:
echo $parsed_json_r->agencies[0]->name;
This assumes that at least one agency is returned and that the agency you are after is the first one if more than one is returned.