I am trying to figure out how to echo the genre value from an object created with this programme wrapper that requests json data from 'The Movie Database'. I'm so stuck and grappling to understand Object-oriented PHP so any help would be great.
I think the fact it is 'nested' (if that's the correct terminology) might be the issue.
<?php
include("tmdb/tmdb-api.php");
$apikey = "myapi_key";
$tmdb = new TMDB($apikey, 'en', true);
$idMovie = 206647;
$movie = $tmdb->getMovie($idMovie);
// returns a Movie Object
echo $movie->getTitle().'<br>';
echo $movie->getVoteAverage().'<br>';
echo '<img src="'. $tmdb->getImageURL('w185') . $movie->getPoster() .'"/></li><br>';
echo $movie->genres->id[28]->name;
?>
All of the other values are echoed just fine but I can't seem to get at genres. The json data looks like this ( some of it).
{
"adult":false,
"backdrop_path":"\/fa9qPNpmLtk7yC5KZj9kIxlDJvG.jpg",
"belongs_to_collection":{
"id":645,
"name":"James Bond Collection",
"poster_path":"\/HORpg5CSkmeQlAolx3bKMrKgfi.jpg",
"backdrop_path":"\/6VcVl48kNKvdXOZfJPdarlUGOsk.jpg" },
"budget": 0,
"genres":[
{ "id": 28, "name": "Action" },
{ "id": 12, "name": "Adventure" },
{ "id": 80, "name": "Crime" }
],
"homepage":"http:\/\/www.sonypictures.com\/movies\/spectre\/",
"id":206647,
"imdb_id":"tt2379713",
"original_language":"en",
"original_title":"SPECTRE",
"overview":"A cryptic message from Bond\u2019s past sends him on a trail to uncover a sinister organization. While M battles political forces to keep the secret service alive, Bond peels back the layers of deceit to reveal the terrible truth behind SPECTRE."
}
$movie->genres->id[28]->name
This assumes that id is an array and you want the item with index number 28 from it. What you want is the item containing an id with the value 28 without knowing its index number.
There's no easy way to get to it. You'd have to loop over the array $movie->genres and output the right one.
Maybe like this:
$n = 28;
// loop over genres-array
foreach($movie->genres as $i=>$g){
// check if id of item has right value and if so print it
if($g->id == $n){
echo $g->name;
// skip rest of loop if you only want one
break;
}
}
Related
I have never needed json previously, so I have almost zero experience...
I am outputting multiple arrays into a json file using the following code:
$file= 'myfile.json';
$contents = array('name' => $name,'busname' => $busname,'busdesc' => $busdesc, etc, etc);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
file_put_contents($file, $newcont);
This is working as expected, and the output gives me something similar to this:
"name": [
"joe blogs",
"random name 2",
"random name 3",
etc,
etc
],
"busname": [
"ABC business",
"DEF business",
"HIJ business",
etc,
etc
],
"busdesc": [
"We do stuff",
"We do other stuff",
"We don't do anything",
etc,
etc
],
etc
Is it possible to (with a simple method) have the output to be more like:
"id1": [ "joe blogs", "ABC business", "We do stuff", etc ]
"id2": [ "random name 2", "DEF business", "We do other stuff", etc ]
"id3": [ "random name 3", "HIJ business", "We don't do anything", etc ]
etc
Layout is not particularly important, but getting them grouped together is.
I have had little success with getting relevant results from Google searches.
The reason I ask for a simple method, is that I am sure I can come up with some fancy loop that counts the number of entries first, then loops to keep adding the relevant data - and that may well be the answer, but I just wanted to know.
Many thanks
Edit:
I have undeleted this as my attempt at fixing did not work.
Here is the code:
$results = mysqli_query($con,"SELECT * FROM membersites WHERE id>0 ORDER BY id, busname");
$totalmem = mysqli_num_rows($results);
while($business = mysqli_fetch_array($results))
{
$r1 = $business['id'];
$id[]=$r1;
$r2 = $business['name'];
$name[]=$r2;
$r4 = $business['busname'];
$busname[]=$r4;
$r5 = $business['busdesc'];
$busdesc[]=$r5;
$all[] = "'id:''".$r1."''name:''".$r2."''busname:''".$r4."''busdesc:''".$r5."'";
}
$contents = array('members' => $all);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
This almost worked as all the data is grouped correctly, however I am only getting one object (members) with all the users inside, not individual objects for each user.
Again, please bare in mind that this is the first project that I have had to output any json files.
Any help will be appreciated :)
Edit 2 (for clarity)
Final output needs to look like this
{
[
{
"id":"1",
"name":"joe blogs",
"busname":"ABC business",
"busdesc":"We do stuff"
},
{
"id":"2",
"name":"joe blogs",
"busname":"random name 2",
"busdesc":"We do other stuff"
},
etc
]
}
This file is going to be read by a mobile app - the app developer has just told me that it need to be in this format.
Apologies for being awkward.
When you loop on your records from DB, build a multi-dimensional array:
while($business = mysqli_fetch_array($results))
{
$all[] = [
'id' => $business['id'],
'name' => $business['name'],
'busname' => $business['busname'],
'busdesc' => $business['busdesc'],
];
// or
$all[] = $business;
// or
$all[ $business['id'] ] = $business;
}
Then you can encode your multidimensional array into JSON like this:
$newcont = json_encode($all, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
the addition of JSON_FORCE_OBJECT will preserve numerical keys (i.e. when you add using $all[])
I'd recommend using PDO for database access instead of mysqli, which was originally developed as a stopgap replacement for the old mysql extension. But, using mysqli this should work:
$result = $con->query("SELECT id, name, busname, busdesc FROM membersites WHERE id > 0 ORDER BY id, busname");
$data = $result->fetch_all();
$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($file, $json);
You should avoid using SELECT * when possible. It reduces overhead, and ensures that you know the order of columns you're receiving. The mysqli_result::fetch_all() function pulls all the records at once, so no need for a loop.
I have a problem with fetching the correct data from a decoded JSON file. I don't know if my question is correct since I don't really know what I am doing for the moment.
So, this is what I don't want to do.
$ln = 'https://api.steamprices.net/v2/csgoprices/?id='.market_hash_name.'&key=XXX';
$link1 = file_get_contents($ln);
$myarray1 = json_decode($link1, true);
echo $myarray1['median_price'];
I am trying to get the price for every steam skin that's being loaded in my code. What this code does is that it loads this api link for every item I load. So if I have 50 items, this link will be loaded 50 times, which is not accepted by the API.
What I want to do, is that I want to load it once, and fetch the prices for every item from that exact link. That link would look like this:
https://api.steamprices.net/v2/csgoprices/?&key=XXX
So, lets say I load it once, and then when I want to apply market_hash_name to it, how do I do?
I assume it is something like this.
$priceJson = file_get_contents('https://api.steamprices.net/v2/csgoprices/?key=XXX');
$priceData = json_decode($priceJson, true);
echo $priceData[''.$market_hash_name.'']['price'];
But it doesn't seem to work. I am sorry for this messy explanation, I an unfamiliar with this.
Note that an example response for the api link looks like this:
{
"-r-H1Z1 Shirt": {
"price": 0.11,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3dxC3m4m0ihzss0MKE6NtIt4qs-JukOX73WgETXYze_pxEBA",
"game": "h1z1"
},
"2016 Invitational Crate": {
"price": 0.09,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6APSjJ6BjX9rGBYZ9ioCPzysSX6hNNacA",
"game": "h1z1"
},
"ANGRYPUG Motorcycle Helmet": {
"price": 0.17,
"image": "https://steamcommunity-a.akamaihd.net/economy/image/iGm5OjgdO5r8OoJ7TJjS39tTyGCTzzQwmWl1QPRXu8oaf69-NOHLAbqw_23aLe8AcRQ8-3uyKA7_CGvsJYds9U65FMF7i6AbXTJ8PDm57EliZdK7KLPuuh3WySnxyXoUgz870MKd7sFTkZq98oW1ORiqAVsCUYfbNu3SUQqvUSGyY__iEw",
"game": "h1z1"
},
Another output
{
"name":"Aces High Pin",
"price":1210,
"have":2,
"max":9,
"rate":95,
"tr":0
}
Well, the json string you provide isn't valid but something like this may help you
<?php
$jsonData=file_get_contents("json.file"); // simply contains your json string as posted
$jsonArray=json_decode($jsonData,true);
$jsonObject=json_decode($jsonData);
$list_of_MHN=array("2016 Invitational Crate","ANGRYPUG Motorcycle Helmet");
print_r($jsonArray);
exit;
foreach($jsonArray as $hash_name=>$arr){
if(in_array($hash_name,$list_of_MHN)){
print_r($arr);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonArray[$list_of_MHN[$i]])){
print_r($jsonArray[$list_of_MHN[$i]]);
}
}
for($i=0;$i<count($list_of_MHN);$i++){
if(isset($jsonObject->$list_of_MHN[$i])){
print_r($jsonObject->$list_of_MHN[$i]);
}
}
?>
It seems that reading the 'conditions' JSON output from Wunderground is very different than readying the output from 'alerts'. Below is a simplified version of my code.
$json_stringalert = file_get_contents("http://api.wunderground.com/api/myKey/alerts/q/MO/Kansas_City.json");
$parsed_jsonalert = json_decode($json_stringalert);
$description = $parsed_jsonalert->{'alerts'}->{'description'};
echo "${description}
The echo is blank, and there are no errors. The output of the the URL looks in part like this;
{
"response": {
"version":"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"alerts": 1
}
}
,"query_zone": "037",
"alerts": [
{
"type": "FIR",
"description": "Fire Weather Warning",
"date": "10:27 am CST on March 2, 2017",
"date_epoch": "1488472020",
"expires": "6:00 PM CST on March 02, 2017",
"expires_epoch": "1488499200",
"tz_short":"CST",
"tz_long":"America/Chicago",
"message": "\u000A...Red flag warning in effect until 6 PM CST this evening for\u000Abreezy northwest winds and low relative humidity values for fire \u000Aweather zones 020, 021, 025, 028, 029, 030, 037, 038, 043, 044, \u000A045, 053, 054, 057, 060, 102, 103, 104, and 105...\u000A\u000AThe National Weather Service in Kansas City/Pleasant Hill has\u000Aissued a red flag warning, which is in effect until 6 PM CST this\u000Aevening. \u000A\u000A* Affected area...fire weather zones 025, 057, 060, 102, 103, \u000A 104, and 105.Fire weather zones 020, 021, 028, 029, 030, 037, \u000A 038, 043, 044, 045, 053, and 054. \u000A\u000A* Wind...sustained northwest winds of 20 mph with higher gusts are\u000A expected this afternoon. \u000A\u000A* Humidity...relative humidity values will fall into the low to\u000A middle 20 percent range. \u000A\u000A* Impacts...any fires that develop will likely spread rapidly. \u000A Outdoor burning is not recommended.\u000A\u000APrecautionary/preparedness actions...\u000A\u000AA red flag warning means that critical fire weather conditions\u000Aare either occurring now, or will shortly. A combination of\u000Astrong winds, low relative humidity, and warm temperatures can\u000Acontribute to extreme fire behavior.\u000A\u000A\u000A\u000ACramer\u000A\u000A\u000A",
"phenomena": "FW",
"significance": "W", ...
and more below.
Can someone please help me write the code to use the 'description' and other output?
$alert_array = $parsed_jsonalert->alerts;
foreach($alert_array as $alert) {
echo $alert->description;
}
In your JSON output the Alerts key is an array so $json->alerts->description doesn't access anything in particular. I'm assuming you want all alerts here and not just a specific key ($json->alerts[0]->description) so you would need to loop over your data like so:
function getAlerts($jsonString)
{
$parsedObj = json_decode($jsonString);
// This is the entire array of alert objects.
$alertsArray = $parsedObj->alerts;
// This next section is only necessary if you want to extract specific
// keys to be returned instead of the entire array of objects. If you
// want everything than just return the $alertsArray variable.
$alerts = array();
foreach ($alertsArray as $alert) {
// Add single key to alerts return array.
// alternatively here is where you would build a filtered array
// of values to return if you need more than one.
$alerts[] = $alert->description;
}
return $alerts;
}
$file = file_get_contents("http://api.wunderground.com/api/myKey/alerts/q/MO/Kansas_City.json");
$alerts = getAlerts($file);
echo implode("\n", $alerts);
I know this is probably a simple question, but I have been struggling with this for a few hours without any solution. I calling the Facebook Graph API and getting a result like so:
{
"og_object": {
"id": "1060581720684416",
"description": "It's\u00a0a chance to donate to your local shelter, volunteer with animals or simply cuddle up to your furry friend.",
"title": "National Dog Day 2016 Quotes: 15 Sayings And Photos Celebrating Man's Best Friend",
"type": "article",
"updated_time": "2016-08-26T19:26:39+0000"
},
"share": {
"comment_count": 0,
"share_count": 481
},
"id": "http://www.ibtimes.com/national-dog-day-2016-quotes-15-sayings-photos-celebrating-mans-best-friend-2407163"
}
I am only interested in accessing the "share_count" and "comment_count" values from this array. Here is the PHP I am trying to use:
$searchTopFBCount = 'https://graph.facebook.com/' . $thisFBLink . '?access_token=xxxxxxxxxx';
$getthisContents = file_get_contents($searchTopFBCount);
$jsonTopFBCount = json_decode($getthisContents,true);
$jsonTopShares = $jsonTopFBCount[0][share]->share_count;
$jsonTopComments = $jsonTopFBCount[0][share]->comment_count;
$jsonTopFBTotal = $jsonTopShares + $jsonTopComments;
No matter what I try, I can't seem to get any values for $jsonTopShares and $jsonTopComments. Any help anyone can give me with this problem would be much appreciated!
As someone mentioned in the comments, I'm not sure why you're using [0] as your data isn't in a nested array. You're also trying to access the array properties like they're objects.
Try this instead:
$jsonTopShares = $jsonTopFBCount['share']['share_count'];
$jsonTopComments = $jsonTopFBCount['share']['comment_count'];
I'm relatively new to mediawiki and has just started last week.
Anyone can point me to the correct direction of getting the top article (based on number of likes) in mediawiki? I've already implemented the fblikebutton extension on every article and managed to retrieve the number of likes for each article.
Code that I used to check the number of likes in each article on different URLS
$query_for_fql = "SELECT like_count FROM link_stat WHERE url = '".$full_url."'";
$fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($query_for_fql);
$response = file_get_contents($fqlURL);
$json_data = json_decode($response);
$fb_like_count = $json_data[0]->like_count;
echo 'Facebook Like:'.$fb_like_count .'<br/>';
eg:
example.com/wiki/index.php?title=ABC (1 like)
example.com/wiki/index.php?title=XYZ (2 likes)
I tried this but this is not working
$highest = 0;
while($highest < $fb_like_count)
{
if($fb_like_count > $highest) //if loop at first
{
$highest = $fb_like_count;
echo "highest value is " . $highest . '<br/>';
}
}
I want to retrieve the content in example.com/wiki/index.php?title=XYZ and display in the "Top Article Page". What should I do next after retrieving the number of likes for each article on each url. The extensions I found for top articles are based on the number of views. But I want to classify the top article based on number of likes.
Thanks a million for helping!
As I said in my comment to you question, FQL is deprecated, and the https://api.facebook.com/method/fql.query endpoint as well.
If you want something future-proof, then you should switch to the /?ids={url1},{url2},... endpoint. You can use this one to generate the comma-separated list of URLs inn the forehand, and then retrieve all the shares in one request, for example
GET /?ids=http://www.techcrunch.com,http://www.google.com
returns
{
"http://www.techcrunch.com": {
"og_object": {
"id": "433841427570",
"title": "TechCrunch",
"type": "website",
"updated_time": "2015-05-27T21:31:39+0000",
"url": "http://techcrunch.com/"
},
"share": {
"comment_count": 0,
"share_count": 20914
},
"id": "http://www.techcrunch.com"
},
"http://www.google.com": {
"og_object": {
"id": "381702034999",
"description": "Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.",
"title": "Google",
"type": "website",
"updated_time": "2015-05-28T07:10:18+0000",
"url": "http://www.google.com/"
},
"share": {
"comment_count": 2,
"share_count": 12340803
},
"id": "http://www.google.com"
}
}
The sorting issue you have is not related to the Facebook API, but PHP.
See
https://developers.facebook.com/docs/graph-api/reference/v2.3/url
Sort JSON object in PHP by a key value
How to sort JSON objects by a certain key's value