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);
Related
I'm currently having an issue getting data from my json files in PHP.
What I got right now is
$jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}', true);
echo ($jsondecoded[0]->chat);
I'm attempting to get the chat information. But it doesn't echo anything. I've been attempting to figure out why this is but I sadly can't find it.
Three errors:
1) Missing ] at the end of the json.
2) You are using the "array assoc" option of json_decode, so it is not returning an object.
3) You cannot echo the chat object.
Try this:
$jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]');
echo ($jsondecoded[0]->chat->username);
$jsondecoded = json_decode('[{"chat": {"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]', true);
Also, remember that you've used true as second parameter for json_decode, it means you're converting the result into a associative array, either remove that true or change your access to:
var_dump($jsondecoded[0]['chat']);
Your json is invalid at end add ']' end of json string, and print array in php use print_r function. '[0]' use for get first element and ['chat'] use for get value of chat key
$jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]', true);
print_r ($jsondecoded[0]['chat']);
output will like
Array
(
[username] => RobloxProtectorKing
[message] => :slender me
[time] => 2018-03-20 01:56:12
)
Here's an example from a template I have. Hopefully it helps.
<?php
/* Status Codes
return 0 = Nothing to Update (n/a)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */
/* Disable Warnings so that we can return ONLY what we want through echo. */
mysqli_report(MYSQLI_REPORT_STRICT);
// First get raw POST input
$raw_post = file_get_contents('php://input');
// Run through url_decode..
$url_decoded = urldecode($raw_post);
// Run through json_decode...
// false to allow for reference to oject. eg. $column->name instead of $column["name"] in the foreach.
$json_decoded = json_decode($url_decoded, false);
$pk_line_item_id = (strlen($json_decoded[0]->value) > 0 ? $json_decoded[0]->value : null);
// INCLUDE DB CONNECTION STRING
include 'php_pdo_mysql_connect.php';
// SQL INSERT query...
$stmt = $link->prepare(" SELECT * FROM tbl_xyz ");
//$stmt->bindParam(':pk_line_item_id', $pk_line_item_id, PDO::PARAM_INT); // INT
// Execute this SQL statement.
$stmt->execute();
// Fetch & Populate the single returned in var $resultSet.
$resultSet = $stmt->fetchAll();
// Returns an array indexed by column number as returned in your result set, starting at column 0.
// https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.7.0/com.ibm.swg.im.dbclient.php.doc/doc/t0023505.html
// If the search record was found, populate it on the html table.
if (($resultSet !== false) && ($stmt->rowCount() > 0)) {
// Set JSON headers
header('Content-type:application/json;charset=utf-8');
// Encode entire $resultSet array to JSON.
$json_encoded = json_encode($resultSet);
// Ready to return as JSON to client side JQuery / Java Script...
echo $json_encoded;
}
?>
I have read a-lot of answers on this but they don't seem to be working.
I have the following code:
$amountoflikes=mysql_query("SELECT * FROM `uc_likes` WHERE `dwable` = '372'");
This returns the following:
If I wanted to echo the value of dwable in the 2nd row for instance (not involving the initial query).
I've tried:
while($row3 = mysql_fetch_assoc($amountoflikes)){
$json[] = $row3;
}
echo json_encode($json);
But this returns null.
I'm currently using PHP 5.5 (native).
I'm not using MySQLi or MySQL PDO.
Can someone tell me where I'm going wrong. Ideally I'd prefer not to use a loop but I don't know if that's possible.
Thanks!
Try declaring $json as an array above the while:
$json = array();
declare your array as follows
$json = array();
and see if you have results before your result
if ($amountoflikes)
{
while(){...}
}
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'];
{
"firstName":"sunny",
"religion": {"holly":"1",
"bolly":"colly",
"nolly":"only"
},
"lonely":"money",
"ronney":"leone",
"honey":"bunny"
}
This is my JSON. I want to get all the data from this and to be stored into some php variables or an array.
I Used the following code to extract data from my JSON. I decoded it first and then stored it in an array..
$val_array = json_decode($jsondata, true);
echo $jsondata;
$AAA = $val_array->firstName;
$BBB = $val_array->religion;
$CCC_id = $val_array->bolly;
$DDD = $val_array->nolly;
$CCC_id = $val_array->lonely;
$DDD = $val_array->ronney;
But it didn't give me any output. Then I used this.
foreach($data['val_array'] as $item)
{
echo $item[0];
}
}
No output. Help??
You get this second param wrong:
$val_array = json_decode($jsondata, true);
$AAA = $val_array['firstName'];
OR
$val_array = json_decode($jsondata, false);
$AAA=$val_array->firstName;
Your JSON is not valid. Remove commas after last elements:
{
"firstName" : "sunny",
"religion" : {
"holly" : "1",
"bolly" : "colly",
"nolly" : "only" # Here
},
"lonely" : "money",
"ronney" : "leone",
"honey" : "bunny" # And here
}
You have an error in your JSON :
"nolly":"only",
"honey":"bunny",
remove the ',' at the end of these 2 lines, then json_decode() will return you an array.
And if you want an object, do not pass second argument to json_decode()
json_decode by default returns an object yet since you are setting the second parameter to true, you are given an associative array with the information instead.
It basically comes down to the fact that either you do not need to fill in the second parameter and get the object you want, or you work with arrays when you set the parameter to true.
A little reading on PHP.net will do you good for further reference since their documentation is well presented, usually commented by others with helpful suggestions and quite clean as well!
$val_array = json_decode($jsondata, true);
$m1=$val_array['firstName'];
$m2=$val_array['lonely'];
$m3=$val_array['ronney'];
$m4=$val_array['honey'];
$m4=$val_array['religion']['holly'];
$m5=$val_array['religion']['bolly'];
$m6=$val_array['religion']['nolly'];
BY using this, we don't have to use foreach loops or inner loops for accessing data. Viola!
This is the json that deepbit.net returns for my Bitcoin Miner worker. I'm trying to access the workers array and loop through to print the stats for my myemail#gmail.com worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble formatting and outputting the workers array.
{
"confirmed_reward":0.11895358,
"hashrate":236.66666667,
"ipa":true,
"payout_history":0.6,
"workers":
{
"myemail#gmail.com":
{
"alive":false,
"shares":20044,
"stales":51
}
}
}
Thank you for your help :)
I assume you've decoded the string you gave with json_decode method, like...
$data = json_decode($json_string, TRUE);
To access the stats for the particular worker, just use...
$worker_stats = $data['workers']['myemail#gmail.com'];
To check whether it's alive, for example, you go with...
$is_alive = $worker_stats['alive'];
It's really that simple. )
You can use json_decode to get an associative array from the JSON string.
In your example it would look something like:
$json = 'get yo JSON';
$array = json_decode($json, true); // The `true` says to parse the JSON into an array,
// instead of an object.
foreach($array['workers']['myemail#gmail.com'] as $stat => $value) {
// Do what you want with the stats
echo "$stat: $value<br>";
}
Why don't you use json_decode.
You pass the string and it returns an object/array that you will use easily than the string directly.
To be more precise :
<?php
$aJson = json_decode('{"confirmed_reward":0.11895358,"hashrate":236.66666667,"ipa":true,"payout_history":0.6,"workers":{"myemail#gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail#gmail.com']; // here's what you want!
?>
$result = json_decode($json, true); // true to return associative arrays
// instead of objects
var_dump($result['workers']['myemail#gmail.com']);