My JSON data variables are empty - php

I have JSON data being fed in which I have set manually for debugging purposes. I'm trying to get the data to be stored in to their own variables (for later DB storage), however, they are empty.
I have tried 2 different things yet it's still appearing as empty when echo'ing them out. Is there a better way of doing this and one that will actually store the data in the required variables?
$json = '[{
"q1":"a",
"q2":"d"
}]';
$questions = json_decode($json, true);
$q1 = $questions->q1; //first method of getting the data
$q2 = $questions['q2']; //second attempted method
echo "q1: ".$q1;
echo "q2: ".$q2;

Get rid of the square braces around the json string:
$json = '{
"q1":"a",
"q2":"d"
}';
$questions = json_decode($json, true);
$q1 = $questions['q1']; //first method of getting the data
$q2 = $questions['q2']; //second attempted method
echo "q1: ".$q1;
echo "q2: ".$q2;
Edit: Since you are planning on sending the information over AJAX, say using something like
JSON.stringify($('#formId').serializeArray());
you may end up with an JSON array, as per your original post. In that case, you may want to do a for loop, or access the question directly like so:
$json = '[{
"q1":"a",
"q2":"d"
}]';
$questions = json_decode($json, true);
foreach($questions as $question) {
$q1 = $question['q1']; //first method of getting the data
$q2 = $question['q2']; //second attempted method
}
// This would also work:
echo $questions[0]['q1'];

Related

How do I get variable values from this JSON array?

So I have a URL that returns the following:
[{"_id":{"champ2_id":63,"champ1_id":2,"role":"TOP"},"count":4,"champ1":{"thirtyToEnd":0,"goldEarned":10727.5,"zeroToTen":0,"minionsKilled":158,"winrate":0,"assists":6.25,"role":"TOP","deaths":6,"kills":4,"wins":0,"totalDamageDealtToChampions":17350.75,"twentyToThirty":0,"tenToTwenty":0,"neutralMinionsKilledTeamJungle":1.75,"killingSprees":0.75,"weighedScore":27214.5375},"champ2":{"twentyToThirty":0,"wins":4,"winrate":1,"kills":5.75,"neutralMinionsKilledTeamJungle":5,"totalDamageDealtToChampions":21881.25,"role":"TOP","assists":7,"tenToTwenty":0,"thirtyToEnd":0,"zeroToTen":0,"goldEarned":12371.75,"killingSprees":1.25,"minionsKilled":140.5,"deaths":4.25,"weighedScore":33166.587499999994}]
I have learned how to get the value of a key in an array when the URL returns something simpler. For example if the URL returns:
{"id":34743514,"accountId":49161997,"name":"League of Fiddle","profileIconId":786,"revisionDate":1514093712000,"summonerLevel":52}
I can echo the id with this code:
$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['id'];
That's easy. But when I try to use the same code for the more complicated stuff, like say I want to get the value of _id champ2_id, I've tried:
$json = file_get_contents(URL);
$data = json_decode($json, true);
echo $data['_id']['champ2_id'];
But this says _id is an undefined index. What am I doing wrong?
should be
$data[0]['_id']['champ2_id'];

json_decode returning NULL [{},{}]

I'm pulling information from our database (entered with GLua) with PHP, then using json_decode to change it to an array to work with but it's returning NULL, whereas other ones are working?
// Get the RapSheet info from 'character_data_store'
$rap = mysql_query("SELECT * FROM `character_data_store` WHERE `character_id` = '$srp_uid' AND `key`='RapSheet'");
while($rapsheet=mysql_fetch_assoc($rap)){
$raps = $rapsheet['value'];
};
Then I use
// Deal with the rapsheet JSON
echo $raps;
$raps = json_decode($rapsheet, true);
echo var_dump($raps, TRUE);
The echo's are to check that it's working, the information is being pulled successfully as it echos, although the var_dump returns
NULL bool(true)
Database contents:
[{"ArrestedBy":"James Scott","Date":1483732483,"Duration":60,"LeaveReason":"Jail time served.","ArrestReason":"test"}]
Any help will be appreciated!
After trying Darren's response:
I tried
$rap = mysql_query("SELECT * FROM `character_data_store` WHERE `character_id` = '$srp_uid' AND `key`='RapSheet'");
$raps = array();
while($rapsheet=mysql_fetch_assoc($rap)){
$raps[] = $rapsheet['value'];
};
// encode
$rap = json_encode($raps, TRUE);
echo $rap;
And that returned:
["[{\"ArrestedBy\":\"James Scott\",\"Date\":1483732483,\"Duration\":60,\"LeaveReason\":\"Jail time served.\",\"ArrestReason\":\"test\"}]"]
So I tried
echo $rap['ArrestedBy'];
and it returned
[
You're trying to access variables that aren't within the proper scope. $rapsheet is only ever accessible within your while() {... loop as it will be that current row of data. What you want to do is create $raps as an array and insert the lines within it. From there you'll be able to json_decode() as you please. Depending on how many rows you've got, you may need to loop over $raps and decode each array element.
$raps = array();
while($rapsheet=mysql_fetch_assoc($rap)){
$raps[] = $rapsheet['value'];
};
// encode
$rap = json_encode($raps, TRUE);

PHP reading json data

I'm new to PHP and web programming at all.I am trying to read some json data from steam API.
Data: http://pastebin.com/hVWyLrfZ
I managed to get to single objects(I believe?).
This is my code:
<?php
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$heroes = reset(reset($data));
//var_dump($heroes);
$wat = reset($heroes);
$antimage = array_values($heroes)[0];
var_dump($antimage);
?>
I want data to be in array like this:
id => name
I mean, array keys should be ids and values should be hero names.
Also,the where I set heroes variable to reset(reset($data)) seems like a bad way of doing what I want, maybe there are better ways?
You can use array_map() function to extract both id and names in two separate arrays and then use array_combine() to create a key-value pair array from the previously extracted arrays.
$url = 'https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=X';
$JSON = file_get_contents($url);
$data = json_decode($JSON, true);
$ids = array_map(function($a) {
return $a['id'];
}, $data['result']['heroes']);
$names = array_map(function($a) {
return $a['name'];
}, $data['result']['heroes']);
$heroes = array_combine($ids, $names);
print_r($heroes);
A simpler more obvious solution is to simply loop thru it. From your pastebin, I see that your data is wrapped in two levels of array so ...
$myResult = [];
foreach ($data['result']['heroes'] as $nameId) {
$myResult[$nameId['id']] = $nameId['name'];
}
(No need to do any reset calls; that's a weird way to get the first element of an array)
Note, for this to work, you must apply the tip by #RamRaider
$data = json_decode($JSON, true);
in order for json_decode to return arrays, not StdClass.

GET info from external Array/API/URL using PHP

I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];

Json strings decode mysql

I am fetching the "form_json" from database which has json saved for all form templates. The code for that is:
<?php
include ('connection.php');
$id = intval($_GET['frmid']);
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");
while ($row = mysqli_fetch_array($results))
{
$url = $row['form_json'];
echo $url; //Outputs: 2
}
?>
Now, I want to decode all these jsons which are being saved in row form_json. Is there anyway to traverse or something?
$json ='{"value":"Form Title","name":"title"}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
This is how we decode but this is for one string / one form template. I can have many json strings / many form templates saved in database. I should be able to decode all.
The best thing you can do for that is, to store the single json strings into an array. Problem is, that your json strings are encoded, so you need to concat them first if you want all results at once:
$json = array();
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");
while ($row = mysqli_fetch_array($results)) {
array_push($json, $row['form_json']);
}
$json = implode(",",$json); // concats all json strings with commas
At this point, you have one large string. To make a successful decode, you have to wrap a container around the string to be a valid parse since your values are already json and you need a container for them:
$json = '{"templates": [' . $json . ']}';
Now you have a valid json string that can be decoded, either as array or object. For better understanding a simple working example:
<?php
$json1 = '{"value":"Form Title","name":"title"}';
$json2 = '{"value":"A Message","name":"message"}';
$arr = array($json1, $json2);
$json = implode(",", $arr);
$json = '{"templates": ['.$json.']}';
$json = json_decode($json, true); // true if you want an array, false if you want an object
echo "<pre>";
print_r($json); // returns a multidimensional array of all templates
echo "</pre>";
?>
$json = '{"value":"Form Title","name":"title"}';
$data = json_decode($json);
$value = $data->value; //will output = Form Title
$title = $data->title; //will output = title
i hope this help

Categories