Parsing a JSON file with multiple levels in a MySQL database - php

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'];

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.

how can two array marge each inside object key are matching it Cross?

I have two array user and game
$user =[
{
"name": "jone",
"id": "100"
},
{
"name": "Peters",
"id": "200"
}
]
$game = [
{
"name": "tennis",
"level": "05",
"user_id": "100"
},
{
"name": "football",
"level": "03",
"user_id": "100"
},
{
"name": "football",
"level": "05",
"user_id": "200"
}
]
I want to get a result like this using PHP / Laravel
$user = [
{
"name": "jone",
"id": "100"
"game": [
{
"name": "tennis",
"level": "05",
"user_id": "100"
},
{
"name": "football",
"level": "03",
"user_id": "100"
}
],
},
{
"name": "Peters",
"id": "200"
"game": [
{
"name": "football",
"level": "05",
"user_id": "200"
}
],
}
],
any one help me
I understand that I should not provide an answer to this "non-question". I still do so, as I think it might carry some learning value.
The idea is, not to cycle each game for each user (as the naive approach would be), as this simply doesn't scale. It is much better to use a matching array and then sort the games into it:
//Prepare matching array
$user_games=array();
foreach ($user as $u) {
$u['game']=array();
$user_games[$u['id']]=$u;
}
//Sort games into matching array
foreach ($game as $g) {
$user_games[$g['user_id']]['game'][]=$g;
}
This way a new game will not create n cycles (n being the number of users), but only one.
print_r($user_games);
creates the desired output. If the user IDs as indices are a problem, just use
print_r(array_values($user_games);

Parsing Rome2Rio json file with PHP

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.

PHP getting values from nested json

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'];
}

Posting to Facebook results randomly in Status messages or Posts

This app is posting to the user's timeline, using PHP and Facebook's PHP API implementation. This is working right now, for over several weeks already.
The following PHP code is being used to post a message:
if($hasPhoto === TRUE)
{
// Post to FB with picture
$facebook->setFileUploadSupport(true);
$result = $facebook->api("/me/photos", "post", array(
'message' => $message,
'place' => $place,
'source' => '#' . $photo
));
}
else
{
// Post to FB without picture
$result = $facebook->api("/me/feed", "post", array(
'message' => $message,
'place' => $place
));
}
This is working properly, except there are two formattings of the $result:
array ('id' => '103240856515XXX', )
array ('id' => '100004900175XXX_103239809849XXX', )
The Graph API documentation tells us the following:
A post from Facebook Platform: https://graph.facebook.com/19292868552_10150189643478553
A status message on the Facebook Page: https://graph.facebook.com/10150224661566729
This means the used PHP code generates posts ór status messages. I don´t see any relation between the textmessages, photos, dates, or authors. It seems to happen randomly.
The following shows the relationship from our data between the format of the id and whether a photo is attached.
select count(*) from fbposts where facebookpostid like '%\_%' and hasphoto = 1; -- 90
select count(*) from fbposts where facebookpostid like '%\_%' and hasphoto = 0; -- 87
select count(*) from fbposts where facebookpostid not like '%\_%' and hasphoto = 1; -- 47
select count(*) from fbposts where facebookpostid not like '%\_%' and hasphoto = 0; -- 54
Why does this behaviour happen? How to force a Post? The reason why this is relevant is because Post does have a Privacy property which I would like to query.
Update:
Querying a status message 545778052106XXX, given by the FB API, with a photo, gives me:
{
"id": "545778052106XXX",
"from": {
"name": "Jeffrey Krist",
"id": "100000226354XXX"
},
"name": "My message!",
"picture": "http://photos-f.ak.fbcdn.net/hphotos-ak-ash3/522827_545778052106XXX_1151562XXX_s.jpg",
"source": "http://sphotos-f.ak.fbcdn.net/hphotos-ak-ash3/s720x720/522827_545778052106XXX_1151562XXX_n.jpg",
"height": 720,
"width": 720,
"images": [
{
"height": 2048,
"width": 2048,
"source": "http://sphotos-f.ak.fbcdn.net/hphotos-ak-ash3/s2048x2048/522827_545778052106XXX_1151562XXX_n.jpg"
}, .. lots more
],
"link": "https://www.facebook.com/photo.php?fbid=545778052106402&set=p.545778052106XXX&type=1",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPXXX.gif",
"place": {
"id": "182665821805XXX",
"name": "A company name",
"location": {
"street": "My street 13", ..
}
},
"created_time": "2012-11-01T08:35:20+0000",
"updated_time": "2012-11-01T08:35:20+0000",
"comments": ...
"likes": ...
}
Querying a post message using a id from the FB API gives me:
{
"id": "100003331805XXX_299609210160XXX",
"from": {
"name": "Some name",
"id": "100003331805XXX"
},
"message": "My message",
"picture": "http://photos-e.ak.fbcdn.net/hphotos-ak-ash3/560724_299609200160XXX_789651XXX_s.jpg",
"link": "https://www.facebook.com/photo.php?fbid=299609200160XXX&set=a.285494101571XXX.69331.100003331805XXX&type=1&relevant_count=1",
"name": "Photo album name",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPXXX.gif",
"actions": [
{
"name": "Comment",
"link": "https://www.facebook.com/100003331805XXX/posts/299609210160XXX"
},
{
"name": "Like",
"link": "https://www.facebook.com/100003331805XXX/posts/299609210160XXX"
}
],
"privacy": {
"value": "ALL_FRIENDS", ...
},
"place": {
"id": "174171872642XXX", ...
},
"type": "photo",
"status_type": "added_photos",
"object_id": "299609200160XXX",
"application": {
"name": "My app", ...
},
"created_time": "2012-12-21T22:33:59+0000",
"updated_time": "2012-12-21T23:30:39+0000",
"likes": ...
"comments": ...
}
Querying a composed id, _ ('100000226354XXX_545778052106XXX'), which is message with a photo, gives me:
{
"error": {
"message": "Unsupported get request.",
"type": "GraphMethodException",
"code": 100
}
}
There is no need to force a post when each status message is a post object.
Status message object 10100948019328597
Post object userid_10100948019328597
Status message object
{
"id": "10100948019328597",
"from": {
"name": "phwd",
"id": "13608786"
},
"message": "Happy Thanksgiving you cool Canadians!",
"updated_time": "2012-10-08T23:17:27+0000",
"likes": {
"data": [
],
"paging": {
"next":
}
}
}
Post object
{
"id": "13608786_10100948019328597",
"from": {
"name": "phwd",
"id": "13608786"
},
"message": "Happy Thanksgiving you cool Canadians!",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/13608786/posts/10100948019328597"
},
{
"name": "Like",
"link": "http://www.facebook.com/13608786/posts/10100948019328597"
}
],
"privacy": {
"description": "Public",
"value": "EVERYONE",
"friends": "",
"networks": "",
"allow": "",
"deny": ""
},
"type": "status",
"status_type": "mobile_status_update",
"created_time": "2012-10-08T23:17:28+0000",
"updated_time": "2012-10-08T23:17:28+0000",
"likes": {
"data": [
]
},
"comments": {
"count": 0
}
}
The best way to check would be to compare /me/statuses vs /me/posts

Categories