How to search Steam game API JSON output? - javascript

I am working with following APIs:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
https://store.steampowered.com/api/appdetails?appids=GAMEID
(gameid example: "730" - counter strike)
My goal with both of these is to search them for data. For example I want the first API to give me a name of a game based on it's ID and the second one to give me specific information about a game for example if it has trading cards (id:29 in the API).
I tried a few things but I am kinda lost on this beacuse I don't really understand JSON so I would really appreciate some help.
I am open to both PHP and JS solutions.

IN PHP, you can use the json_decode() function to convert JSON data into an array. You can them access the values as you do for a classic array :
$appID = 730 ;
$url = 'https://store.steampowered.com/api/appdetails?appids=' . $appID ;
$content = file_get_contents($url) ; // retrieve the JSON data string from the website
$data = json_decode($content, true); // convert the JSON string into PHP array
echo $data[$appID]['data']['name'] ; // Counter-Strike: Global Offensive
var_dump($data[$appID]['data']['is_free']); // bool(true)

Related

How to read a JSON Array in php without any key?

I have a JSON formed #Javascript and passed to PHP via AJAX , problem is that I cannot assign keys to each JSON Object inside the JSON Array .
The JSON Array looks something like this :
[{"jobId":"90","cname":"Subhasish","removal_id":101,"quantity":"3"},{"jobId":"90","cname":"Subhasish","removal_id":102,"quantity":"2"},{"jobId":"90","cname":"Subhasish","removal_id":103,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":104,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":105,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":106,"quantity":"5"},{"jobId":"90","cname":"Subhasish","removal_id":107,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":108,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":109,"quantity":"4"}]
,Now , in PHP ,how to iterate the data , I am a newbie to PHP , so please excuse me if I am asking a very silly question.
The link you provided has examples with key, mine is without key.
Thanks
$json = '[{"jobId":"90","cname":"Subhasish","removal_id":101,"quantity":"3"},{"jobId":"90","cname":"Subhasish","removal_id":102,"quantity":"2"},{"jobId":"90","cname":"Subhasish","removal_id":103,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":104,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":105,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":106,"quantity":"5"},{"jobId":"90","cname":"Subhasish","removal_id":107,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":108,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":109,"quantity":"4"}]';
$array = json_decode($json,true);
foreach($array as $item) {
echo $item['jobId']."-".$item['cname']."-".$item['removal_id']."-".$item['quantity']."\n";
}
Output
90-Subhasish-101-3
90-Subhasish-102-2
90-Subhasish-103-4
90-Subhasish-104-4
90-Subhasish-105-0
90-Subhasish-106-5
90-Subhasish-107-0
90-Subhasish-108-0
90-Subhasish-109-4
Example
Using json_decode($json_object).
$json = json_decode($json_object);
foreach($json as $j){
print_r($j)
}

Adding grahps in HTML based on data from database (PHP)

I have a table called flagged_posts with the following rows:
id
thought_id (id of the post being flagged)
user_id (id of the user who is flagging the post)
I am trying to implement a graph which (for now) will show how many flagged posts have occured ed for the current date (x-axis will show days, i.e. monday, tuesday etc, y-xis will show number of incidents).
I have seen charts.js but, I am unsure whether these charts can be used based on database data. I.e. if monday has 10 flagged incidents, $mon_flagged = 10, then use the variable to display data in the graph? or in another way which automatically gets data from db?
https://www.amcharts.com/tutorials/using-php-to-hook-up-charts-to-mysql-data-base/You first need to build your data into an array that will be in a useful format for the chart library.
After you have selected the relevant data, format it into an array something like this:
function formatDataForChartsJs($result){
while ( $row = mysql_fetch_assoc( $result ) ) {
if($row['post_is_flagged']) {
$data[$row['date_created']] += 1;
}
}
return $data
}
Then you should end up with an array suitable for use with your javascript charting library. Something like this:
$data = [
2016-03-7 => 10
2016-03-08 => 15
...
]
You then need to understand how you will pass the data to front end so that you can use your data with a javascript chart library.
The normal way to do this it to take your php data variable and encode it as a json string.
$data = fetchData();
$formattedData = formatDataForChartsJs();
$dataAsJsonString = json_encode($formattedData);
Then in your view:
<script type=text/javascript>
var graphData = <?php echo $dataAsJsonString ?>
//use your graph data variable with chart.js or other javascript graph library
</script>
There is a good tutorial here, but I would advise using json_encode rather than their approach to printing a JSON string.
https://www.amcharts.com/tutorials/using-php-to-hook-up-charts-to-mysql-data-base/

javascript Arrays to mySQL

I have a file called translations.js, this js does got have two vars. This two vars are containing over 20.000 words.
var english = ["word1", "word2", "word3", "word4", ...]
var farsi = ["translation1", "translation2", "translation3",
"translation3"]
So i want to add all the values to a table on mySQL.
How can I do that quick and good? I want to do this with PHP.
I have the table "translations", containing this columns: id, english, farsi.
I want that all the words should be added into the database. So i thought to split this file into english.js and farsi.js - after that I wanted to use "explode" on both variables, foreach till no "" is there and then i wanted to add them step by step.
Is there a easier way? Does this way make sense?
Thank you!
If those arrays are valid json by themselves you could make a json file for each and read the file using file_get_contents(), then use json_decode() to convert to php array.
Loop over array to do inserts.
Alternative would be to load those variables into an html page and use ajax to post the whole array to php script. Loop over array received in $_POST
Does have english array and farsi array exactly the same size?
(I suppose yes).
Maybe you can create a file english.json and a farsi.json;
each file must only contains ["word1", "word2", "word3"] so remove var english =.
then use
$listEnglish = json_decode(file_get_contents('path_to_english.json'));
$listFarsi = json_decode(file_get_contents('path_to_farsi.json'));
It should generate a php array for each one.
finally loop on it
for($i = 0; $i < sizeof($listEnglish); $i++)
{
$englishWord = $listEnglish[$i];
$farsiWord = $listFarsi[$i];
//Then you insert
INSERT INTO translation(english, farsi) VALUES ($englishWord, $farsiWord);
}

Populate PHP Array Values in Javascript

Here is my code:
I am getting data from mysql query and getting array of values. But i am not able to populate in javasript. could you please any one help me out...
PHP Code:
$parishFamilyInfo = $parishFamilyInfoBO->sendBirthdayGreeting($personalInfoSearchDO, $parishFamilyInfoSearchDO);
foreach ($parishFamilyInfo as $parishFamily){
if(!empty($parishFamily->email)){
print_r($parishFamily);
}
}
JavaScript:
$(document).ready(function(){
var t = $('#people').bootstrapTransfer(
{'target_id': 'multi-select-input',
'height': '15em',
'hilite_selection': true});
t.populate([ /*here i need to populate php array value*/
{
value:"<?php print_r($parishFamily->email);?>",
content:"<?php print_r($parishFamily->name);?>"
},
]);
//t.set_values(["2", "4"]);
//console.log(t.get_values());
});
print_r is only for debugging. It's not for anything else. Let me quote the documentation:
print_r — Prints human-readable information about a variable
As stated above, it is a debugging function that's used to print the contents of a variable in a more readable manner. It just returns a string — JavaScript does not and will not understand this format.
Use JSON (JavaScript Object Notation) instead. It is is a light-weight data interchange format that is very popular nowadays. You can use the built-in function json_encode to create the JSON representation of your PHP array and then transfer it to JavaScript. JSON being language independent and based on the JavaScript scripting language, your JavaScript code will now be able to parse the array:
t.populate([
{
value: <?php echo json_encode($parishFamily->email); ?>,
content: <?php echo json_encode($parishFamily->name); ?>
},
]);

Passing Mysql data to PHP array then to javascript

Let me start by explaining the situation:
I have a MySql table that contains several columns, of which a user id, a race id, a lap time, a lap number and I want to put this information into an array in PHP which I will then send to a java script.
My JavaScript array should end up looking like this :
first row:
[laptime1 user1, laptime2 user1, laptime3 user1,...]
second row:
[laptime1 user2, laptime2 user2, laptime3 user2,...]
Here's my current situation:
I first tried to test this situation for a single user and ran into lots of problems because my lap times in MySql are floats and when using json_encode it turned everything into strings, which did not work for my javascript as it started outputting the wrong values.
For example:
The first value was "8" instead of "84,521", then the second value was "4", etc..)...
Sadly, I found a potential solution with the numeric check option, but cannot use it as my hosting runs a PHP version that doesn't support it.
So I found the following solution, which I fiddled with a bit and that works for a single user (it might look messy to you, I'm really a beginner and punching above my weight, but it works) :
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
while(($result = mysql_fetch_array($query))) {
$data[] = (float)$result['racelaptime'];
}
$script = $script . "\nvar myArray = new Array(";
foreach ($data as $key => $value){
if ($key < (count($data)-1)){
$script = $script . $value . ',';
}
else {
$script = $script . $value . ");\n";
}
}
This outputs an array in JavaScript that looks like this :
myArray=[84.521,83.800,81.900]
Which is great, as this is exactly what my java script requires as input (time in seconds, separated by commas for each lap).
Now I would like to implement the multiple user element but I'm stumped as to how I can work that out...
My MySQL query is still sorted by race lap but I also kind of need to sort the data by user id as I want all the laps of each user sorted in 1 row, Also, the user id is unknown to me and can vary (depends which user posts the time) so I can't really do a "if userid==1 save this here and then go to next one".
Should I use a foreach statement in the while loop that stores the data, but how can I tell him to store all the laps by the same user in the first row (and the next user in the second row, etc...) without using tons of SQL queries ?
If you can offer a more elegant solution than my current one for passing the PHP array to JavaScript, I would be more than happy to make changes but otherwise a simple solution using the current "setup" would be great too (hope it's all clear enough).
Any help would be very much appreciated, thanks in advance !
For multiple user element I would use a multidimensional array >
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
// Loop the DB result
while(($result = mysql_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['userid'], $data)){
// Create array for current user
$data[$result['userid']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['userid']][] = $result['racelaptime'];
}
// Echo json data
echo json_encode($data);
Now what you need to do on the Javascript side when handling this array is to go through each of the user
$.each(data, function(key, value){
// Use parseFloat to keep the decimal value
alert(key + ' Has the following values - ' + value);
// If you want to display the racing values you simply
$.each(value, function(k, parseFloat(v)){
alert(v);
})
})
Is this what you needed or am I completely out of the scope?

Categories