How to traverse array after decoding JSON [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP JSON decode - stdClass
I have a JSON file with a structure like this:
[{"key_mappings": "",
"screen2_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen2_thumb.png",
"video_url": "http://www.youtube.com/watch?v=S7MDxObgJxw",
"rating": "Teen",
"screen1_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen1_thumb.png",
"metascore": 43.63,
"height": 500,
"screen3_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen3_thumb.jpg",
"stage3d": false,
"screen3_url": "http://games.mochiads.com/c/g/siegius-arena/screen3.jpg",
"recommendation": 5,
"coins_revshare_enabled": null,
"category": "Fighting",
"screen4_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen4_thumb.png",
"uuid": "6789c7e3-fd27-345e-85d9-e6a58165ae57",
"author": "Juice-Tin",
"thumbnail_large_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_200x200.png",
"author_link": "https://www.mochimedia.com/community/profile/Juice-Tin",
"controls":
[["C", "Item"],
["V", "Spell"],
["X", "Heavy Attack"],
["Z", "Fast Attack"],
["fire", "na"],
["jump", "na"],
["movement", "arrow"]],
"languages": ["en"],
"swf_url": "http://games.mochiads.com/c/g/siegius-arena/Siegius%20Arena_.swf",
"recommended": true,
"game_tag": "e0e05c5c5fd1a61b",
"achievements_enabled": false,
"zip_url": "http://games.mochiads.com/c/g/siegius-arena.zip",
"screen1_url": "http://games.mochiads.com/c/g/siegius-arena/screen1.png",
"updated": "2012-10-25T15:47:01.953336-08:00",
"description": "Fight in arena battles and upgrade your gladiator in this Action-RPG about betrayal and revenge.",
"tags": ["siegius", "arena", "gladiator", "rome", "battle", "fight", "upgrade", "rpg", "fans", "en"],
"swf_file_size": 10142842,
"leaderboard_enabled": false,
"game_url": "http://www.mochimedia.com/games/siegius-arena",
"screen2_url": "http://games.mochiads.com/c/g/siegius-arena/screen2.png",
"slug": "siegius-arena",
"categories": ["Action", "Fighting"],
"instructions": "",
"name": "Siegius Arena",
"created": "2012-10-25T12:47:55.080005-08:00",
"control_scheme": "{\"C\": \"Item\", \"fire\": \"na\", \"jump\": \"na\", \"V\": \"Spell\", \"X\": \"Heavy Attack\", \"Z\": \"Fast Attack\", \"movement\": \"arrow\"}",
"popularity": 0,
"feed_approval_created": "2012-10-25T13:30:53.505710-08:00",
"coins_enabled": null,
"thumbnail_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_100x100.png",
"screen4_url": "http://games.mochiads.com/c/g/siegius-arena/screen4.png",
"alternate_url": "",
"resolution": "800x500",
"width": 800}]
Then, I have a foreach statement which adds the data to a MYSQL database:
foreach($result as $key => $value) {
if($value) {
mysql_query("INSERT INTO `games_db`.`Games` (`title`, `description`, `image`, `category`, `page`, `rating`, `width`, `height`, `tags`) VALUES ('$value->name', '$value->description', '/images/$pageid.jpg', '$category', '$pageid', '$value->rating', '$value->width', '$value->height', '$value->tags')")
}
My question is, What do I have to do to show and insert the tags from the JSON file? Currently, When I run this page, the data for the "tags" column just says "Array".

You can use json_decode() as so:
$jsonString = '[{"key_mappings": "", "screen2_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen2_thumb.png", "video_url": "http://www.youtube.com/watch?v=S7MDxObgJxw", "rating": "Teen", "screen1_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen1_thumb.png", "metascore": 43.63, "height": 500, "screen3_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen3_thumb.jpg", "stage3d": false, "screen3_url": "http://games.mochiads.com/c/g/siegius-arena/screen3.jpg", "recommendation": 5, "coins_revshare_enabled": null, "category": "Fighting", "screen4_thumb": "http://games.mochiads.com/c/g/siegius-arena/screen4_thumb.png", "uuid": "6789c7e3-fd27-345e-85d9-e6a58165ae57", "author": "Juice-Tin", "thumbnail_large_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_200x200.png", "author_link": "https://www.mochimedia.com/community/profile/Juice-Tin", "controls": [["C", "Item"], ["V", "Spell"], ["X", "Heavy Attack"], ["Z", "Fast Attack"], ["fire", "na"], ["jump", "na"], ["movement", "arrow"]], "languages": ["en"], "swf_url": "http://games.mochiads.com/c/g/siegius-arena/Siegius%20Arena_.swf", "recommended": true, "game_tag": "e0e05c5c5fd1a61b", "achievements_enabled": false, "zip_url": "http://games.mochiads.com/c/g/siegius-arena.zip", "screen1_url": "http://games.mochiads.com/c/g/siegius-arena/screen1.png", "updated": "2012-10-25T15:47:01.953336-08:00", "description": "Fight in arena battles and upgrade your gladiator in this Action-RPG about betrayal and revenge.", "tags": ["siegius", "arena", "gladiator", "rome", "battle", "fight", "upgrade", "rpg", "fans", "en"], "swf_file_size": 10142842, "leaderboard_enabled": false, "game_url": "http://www.mochimedia.com/games/siegius-arena", "screen2_url": "http://games.mochiads.com/c/g/siegius-arena/screen2.png", "slug": "siegius-arena", "categories": ["Action", "Fighting"], "instructions": "", "name": "Siegius Arena", "created": "2012-10-25T12:47:55.080005-08:00", "control_scheme": "{\"C\": \"Item\", \"fire\": \"na\", \"jump\": \"na\", \"V\": \"Spell\", \"X\": \"Heavy Attack\", \"Z\": \"Fast Attack\", \"movement\": \"arrow\"}", "popularity": 0, "feed_approval_created": "2012-10-25T13:30:53.505710-08:00", "coins_enabled": null, "thumbnail_url": "http://games.mochiads.com/c/g/siegius-arena/_thumb_100x100.png", "screen4_url": "http://games.mochiads.com/c/g/siegius-arena/screen4.png", "alternate_url": "", "resolution": "800x500", "width": 800}]';
$jsonObject = json_decode($jsonString);
foreach ($jsonObject->tags as $tag) {
echo $tag . PHP_EOL;
//Do something
}
If you use less than PHP 5.2.0, you can use the JSON PECL Extension
I should also add that you shouldn't use the mysql functions any more - they're deprecated. See: Why shouldn't I use mysql_* functions in PHP?

use json_decode():
json_decode — Decodes a JSON string
$jsonObject = json_decode($string); // returns an object
or:
$jsonArray = json_decode($string, true); // if second argument is true, returned object will be converted to an associative array
Edit:
as suggested by #nickhar: NOTE: You need PHP 5.2.0 or above to use json_decode()
Or one of the emulations floating around – #mario

Related

How to get filenames as array in string using PHP?

In database, the html contents are stored as string.
In there, I want to get the file names as array.
For example, the string is:
"info": [], "title": "Neues Kapitel", "videos": [], "children": [], "html1": "<p><img class=\"fr-dib fr-fil\" src=\"files\/1\/first.jpg" style=\"width: 300px;\"></p>","info": [], "title": "Neues Kapitel", "videos": [], "children": [], "html2": "<p><img class=\"fr-dib fr-fil\" src=\"files\/1\/second.jpg" style=\"width: 300px;\"></p>"
So the result file names will be: ['first', 'second']
Anyone who knows, please let me know.
Thanks.

json - how to get data from json where user's input will come on %s [duplicate]

This question already has answers here:
PHP replace wildcards (%s, %d) in string with vars
(2 answers)
Closed 3 years ago.
I've got a JSON file which looks like this
{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}
So I'm getting users social links from a form, but only the user's ID of social link eg.https://facebook.com/ID. I'm storing the users ID in JSON file in database. I'm using PHP. How do I add the users ID in that '%s' and display the link.
To put together the information using the JSON data you have, you would use either sprintf() or printf() (the only difference being the printf() directly outputs the data sprintf() returns a string). The information on the manual pages shows how things like %s works.
So the code would look something like...
$id = 123;
$userName = "User name";
$json = '{
"facebook": {
"icon": "fab fa-facebook",
"title": "Facebook",
"url": "https://facebook.com/%s"
},
"instagram": {
"icon": "fab fa-instagram",
"title": "Instagram",
"url": "https://instagram.com/%s"
}
}';
$socialMedia = json_decode( $json, true );
echo echo '<a href="'.sprintf($socialMedia["facebook"]["url"], $id).'">'.
$userName.'</a>';
Which outputs...
User name

It is possible to set fields which i want to get in overpass api&

For example. I want to get coordinates of all node buildings in bbox.
PHP
$queryBuildings="[out:json];node['building']({$y1},{$x1},{$y2},{$x2});out;";
$data = file_get_contents("http://overpass-api.de/api/interpreter?data={$queryBuildings}")
One element from result:
{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}
I want to get only lon and lat fields it's possible?
You can use skeleton print mode (out skel) which omits all tags, thus being slightly shorter. So your request should become: [out:json];node['building']({$y1},{$x1},{$y2},{$x2});out skel;
Currently csv output mode ([out:csv]) is the only mode where you can select the fields to be shown.
<?php
$data = '{
"type": "node",
"id": 29537155,
"lat": 54.6744568,
"lon": -2.1421066,
"tags": {
"building": "house",
"description": "Abandoned (2007). Associate with lead mine workings above it?",
"name": "Flushiemere House"
}
}';
$test = json_decode($data);
var_dump($test->lon);
First use json_decode to parse the response body:
$parsed_data = json_decode($data);
Then you can access the various fields like so:
$lat = $parsed_data->lat;
$lon = $parsed_data->lon;

Manipulate json data, into a new json array

{
"name": "2Pac",
"album": "All Eyez on Me",
"track": "All Eyez on Me",
"duration": "5:08",
"trackNo": ""
},
{
"name": "2Pac",
"album": "2Pac Greatest Hits",
"track": "Keep Ya Head Up",
"duration": "4:24",
"trackNo": "1"
},
{
"name": "2Pac",
"album": "2Pac Greatest Hits",
"track": "2 Of Amerikaz Most Wanted",
"duration": "4:07",
"trackNo": "2"
},
{
"name": "50 Cent",
"album": "Get Rich Or Die Tryin%27",
"track": "P.I.M.P.",
"duration": "4:10",
"trackNo": "11"
},
{
"name": "50 Cent",
"album": "Get Rich Or Die Tryin%27",
"track": "Like My Style",
"duration": "3:13",
"trackNo": "12"
},
I have lots of json data formatted this way and was looking for a way to manipulate the data so that it only has one artist name and then the albums for that artist then songs within each album. PHP would be fine so I can convert things, Any help would be appreciated.
Use these:
json_decode
array_map, array_filter, for loops, what you like
json_encode
Basically it boils down to:
parse
mangle
format
I'll leave the exercise to you, but browsing these functions and similar questions here should get you started. If you have anything to show then, you may ask for more specific help.

PHP/JSON Skipping Over Information? Multiple Test Cases Provided

I've got another JSON / PHP question. I'll start off by posting a brief segment of the JSON, at least enough to convey my point:
"results": [
{
"members": [
{
"side": "majority",
"rank": 1,
"title": "Chairman",
"legislator": {
"bioguide_id": "T000464",
"birthday": "1956-08-21",
"chamber": "senate",
"contact_form": "http://www.tester.senate.gov/Contact/index.cfm",
"crp_id": "N00027605",
"district": null,
"facebook_id": "210573031664",
"fax": "202-224-8594",
"fec_ids": [
"S6MT00162"
],
"first_name": "Jon",
"gender": "M",
"govtrack_id": "412244",
"icpsr_id": 40702,
"in_office": true,
"last_name": "Tester",
"lis_id": "S314",
"middle_name": null,
"name_suffix": null,
"nickname": null,
"office": "706 Hart Senate Office Building",
"party": "D",
"phone": "202-224-2644",
"senate_class": 1,
"state": "MT",
"state_name": "Montana",
"state_rank": "junior",
"term_end": "2019-01-03",
"term_start": "2013-01-03",
"thomas_id": "01829",
"title": "Sen",
"twitter_id": "testerpress",
"votesmart_id": 20928,
"website": "http://www.tester.senate.gov",
"youtube_id": "senatorjontester"
}
},
{
"side": "majority",
"rank": 2,
"title": null,
"legislator": {
"bioguide_id": "P000590",
"birthday": "1963-01-10",
"chamber": "senate",
"contact_form": "http://www.pryor.senate.gov/public/index.cfm?p=ContactMe",
"crp_id": "N00013823",
"district": null,
"facebook_id": "9248638978",
"fax": "202-228-0908",
"fec_ids": [
"S0AR00028"
],
"first_name": "Mark",
"gender": "M",
"govtrack_id": "300080",
"icpsr_id": 40301,
"in_office": true,
"last_name": "Pryor",
"lis_id": "S295",
"middle_name": null,
"name_suffix": null,
"nickname": null,
"office": "255 Dirksen Senate Office Building",
"party": "D",
"phone": "202-224-2353",
"senate_class": 2,
"state": "AR",
"state_name": "Arkansas",
"state_rank": "senior",
"term_end": "2015-01-03",
"term_start": "2009-01-06",
"thomas_id": "01701",
"title": "Sen",
"twitter_id": "senmarkpryor",
"votesmart_id": 35,
"website": "http://www.pryor.senate.gov",
"youtube_id": "senatorpryor"
}
},
Alright - the information I'm tryin to grab is the title of each legislator, as well as the bioguide_id. The code I'm using to parse the information is as follows:
$url1 = 'http://congress.api.sunlightfoundation.com/committees?fields=members&apikey=XXXXXXXXXXX&per_page=20&page=1';
$response1 = file_get_contents($url1);
$key1 = json_decode($response1, true);
foreach ($key1['results'] as $value){
$title_1 = $value['members'][0]['title'];
if($title_1 == NULL){
$title_1 = "NULL";
}
echo $title_1 . '<br/>' . $value['members'][0]['legislator']['bioguide_id'] . '<br/>';
}
However, the results from running the script are as follows:
Chairman
T000464
Chairman
M001170
Chairman
B001265
Chairman
L000261
Chairman
B000711
Chairman
K000384
Chairman
B001267
Chairman
C001070
Chairman
W000802
Chairman
M001176
Chairman
N000032
Chairman
K000367
Chairman
G000555
NULL
L000174
Chairman
H001069
Chairman
B001267
Chairman
D000607
Vice Chairman
B000243
Chairman
S000148
Vice Chairman
S000148
Upon first glance, I thought that things looked fishy because of the amount of Chairmen titles floating about (when there should be several NULL in between the Chairmen) and the second bioguide_id isn't the correct bioguide_id for the second position (Chairman & T000464 looks correct, but the next one shouldn't be Chairmen M001170, but NULL P000590). I've switched the $value['members'][0]... to $value['members'][1], and was able to get the second address, but the results weren't correct. Is there anything that anyone can see that would allow me to grab the correct information? From how I've worked with my other JSON files, it would seem that I'm not doing this dramatically incorrect. Thanks in advance (I know it was long).
Your foreach is looping through the sets of results, not the sets of members.
Here is a working foreach that I have confirmed works:
foreach ($key1['results'][0]['members'] as $value) {
$title_1 = $value['title'];
if ($title_1 == NULL) {
$title_1 = "NULL";
}
echo $title_1 . '<br/>' . $value['legislator']['bioguide_id'] . '<br/>';
}

Categories