I know it's my syntax, but can't find the problem.
I normally use a loop to turn any json keys into variables like this:
Sent JSON: [{\"name\":\"dolly\",\"page\":\"A4\"}]
$object = json_decode(stripslashes($_POST['myData']));
foreach ($object[0] as $key => $value)
{
$$key = preg_replace('/--+/',' ',$value);
}
So now, eg, I have $page = "A4". Works fine.
Now, rather than looping through like that, I just want to access the 'page' key (that I know is going to be there every time), and disregard anything else.
I thought this would do it, but it falls over with "Cannot use object of type stdClass as array":
$object = json_decode(stripslashes($_POST['myData']));
$page = $object[0]['page'];
This doesn't error out, but it returns nothing:
$object = json_decode($_POST['myData']);
$p = $object[0]->page;
As does
$p = $object->page;
What am I screwing up here?
Thanks for taking a look.
This seems to work fine for me?
$a='[{\"name\":\"dolly\",\"page\":\"A4\"}]';
$o=json_decode(stripslashes($a));
var_dump($o[0]->page);
string(2) "A4"
Does that help?
You will need to combine your approaches ;-)
$object = json_decode(stripslashes($_POST['myData'])); // note the stripslashes() here!
$p = $object[0]->page;
As the object encoded is an array, you do need to get the first element and then the object property as you did in your second snippet of code. You just forgot to apply stripslashes() so that json_decode() failed.
Related
I'm having a difficult time appending each element in an array I have in PHP for multiple OneSignal tags. Here is the result of my current JSON encoded array:
[{"value":"email#address.com"},
{"value":"email#address.com"},
{"value":"email#address.com"}]
Desired output:
[{"key":"user_email","relation":"=","value":"email#address.com"},
{"key":"user_email","relation":"=","value":"email#address.com"},
{"key":"user_email","relation":"=","value":"email#address.com"}]
Here is my current PHP code:
$jsonData = array();
$allStaffInit = mysql_query("Select * from users");
while ($staffrow = mysql_fetch_object($allStaffInit)){
$jsonData[] = $staffrow;
}
echo json_encode($jsonData);
Any help is greatly appreciated! Thanks!
Try replacing
$jsonData[] = $staffrow;
with
$object = new stdClass();
$object->key = "user_email";
$object->relation = "=";
$object->value = $staffrow->value;
$jsonData[] = $object;
I am typing this in a browser, so cannot test, but you get the idea (if you don't get the idea, ask in comments :)
If you must use the mysql_ functions, you don't need to manually construct an object or array, just get the result set as an array and use that.
while ($staffrow = mysql_fetch_assoc($allStaffInit)){
$jsonData[] = $staffRow;
}
But I seriously recommend you at least upgrade to using the mysqli extension instead. You won't really have to adjust your code much.
http://php.net/manual/en/book.mysqli.php
Here is the JSON response in which I need your help.
I need to access "age" key inside 'attribute'.
I really tried every possible ways that i could get. So can u please try to help me out :)
Another option, is that when you call json_decode by default you get a php object, however, if you add an optional boolean parameter you get an array which can be easier in situations like this to access nested elements.
// $data is the original json string
$json = json_decode($data, true);
print_r($json);
There are 2 ways I can see checking the json you just provided, one is by iterating the array, and the other one is accessing it by index:
$json = json_decode($response);
foreach ($json as $item) {
$value = $item->item->attribute->age->value;
var_dump($value);
}
the other way:
$value = $json[0]->item->attribute->age->value;
{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}
I am trying to fetch description from the weather from the json above but getting errors in php. I have tried the below php code:
$jsonDecode = json_decode($contents, true);
$result=array();
foreach($jsonDecode as $data)
{
foreach($data{'weather'} as $data2)
{
echo $data2{'description'};
}
}
Any help is appreciated. I am new in using json.
You have to use square brackets ([]) for accessing array elements, not curly ones ({}).
Thus, your code should be changed to reflect these changes:
foreach($data['weather'] as $data2)
{
echo $data2['description'];
}
Also, your outer foreach loop will cause your code to do something completely different than you intend, you should just do this:
foreach($jsonDecode['weather'] as $data2)
{
echo $data2['description'];
}
Your $jsonDecode seems to be an array, so this should work-
foreach($jsonDecode['weather'] as $data)
{
echo $data['description'];
}
You can access data directly with scopes
$json = '{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}';
$jsonDecode = json_decode($json, true);
echo $jsonDecode['weather'][0]['description'];
//output Sky is Clear
As you can see wheater` is surrounded with scopes so that means it is another array. You can loop throw that array if you have more than one result
foreach($jsonDecode['weather'] as $weather)
{
echo $weather['description'];
}
Live demo
If the result of decode is an array, use:
$data['weather']
If the result is an object, use:
$data->weather
you have to access "weather" with "[]" operator
like this,
$data["weather"]
There is several things worth answering in your question:
Q: What's the difference between json_decode($data) and json_decode($data, true)?
A: The former converts JSON object to a PHP object, the latter creates an associative array: http://uk1.php.net/json_decode
In either case, there is no point on iterating over the result. You probably want to access just the 'weather' field:
$o = json_decode($data) => use $weather = $o->weather
$a = json_decode($data, true) => use $weather = $a['weather']
Once you have the 'weather' field, look carefully what it is:
"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}]
It's an array, containing a single object. That means you will either need to iterate over it, or use $clearSky = $weather[0]. In this case, it does not matter which approach of json_decode did you choose => JSON array is always decoded to a PHP (numeric indexed) array.
But, once you get $clearSky, you are accessing the object and it again matters, which approach you chose - use arrow or brackets, similarly to the first step.
So, the correct way to get for exaple the weather description would be either of these:
json_decode($data)->weather[0]->description
json_decode($data, true)['weather'][0]['description']
Note: In the latter case, dereferencing result of the function call is supported only in PHP 5.4 or newer. In PHP 5.3 or older, you have to create a variable.
Note: I also encourage you to always check if the expected fields are actually set in the result, using isset. Otherwise you will try to access undefined field, which raises an error.
I keep running into the error Warning: Invalid argument supplied for foreach() and for the life of me I can't figure out why. Here is my relevant code:
$Ids = $_POST["param-0"];
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
stripslashes($decodedJson);
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
$Ids is a string from a previous file that is encoded with json_encode. I added the stripslashes because it was recommended in another question on Stack Overflow, but it didn't help. If I change the beginning of the foreach loop to beforeach($toReturn as $id) the error goes away. Thanks!
edit: in the previous file, $_POST["param-0"] is an integer array that I returned with json_encode. With the testing data I am working with right now, ["15","18"] is what is being passed.
First you need to decode the json (which you already did)
$decodedJson = json_decode($Ids, True);
Then to grab each value from the json and, for example, echo it. Do this:
foreach ($decodedJson as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $value) {
echo $value; // This will show jsut the value f each key like "var1" will print 9
// And then goes print 16,16,8 ...
}
}
From top to botton:
$Ids = $_POST["param-0"];
This will trigger a notice if input data does not have the exact format you expect. You should test whether the key exists, for instance with isset().
$toReturn = array();
$decodedJson = json_decode($Ids,TRUE);
This will return null if input data is not valid JSON. You should verify it with e.g. is_null().
stripslashes($decodedJson);
If input data was valid we'll first get a warning:
Warning: stripslashes() expects parameter 1 to be string, array given
Then, if our PHP version is very old we'll have our array cast to a string with the word Array in it, and if our PHP version is recent we'll get null. Whatever, our data is gone.
If input data wasn't valid, we'll get an empty string.
foreach($decodedJson as $id)
{
... do stuff with $toReturn...
}
Neither null or strings (empty or not) are iterable. There's no nothing to do here. Our data is gone forever :_(
It ended up I was incorrectly encoding what I wanted decoded. All is well again, thanks for everyone's help!
I'm not a PHP developer so I may be doing something wrong. I'm trying to decode JSON string and insert some values to mysql database. I'm getting a valid array of json objects (tested with jsonlint), so I'm adding them one by one to database. But php throws :
<b>Fatal error</b>: Cannot use object of type stdClass as array error.
This is the code :
$array = json_decode(stripslashes($_POST['data']));
for($i = 0, $l = sizeof($array); $i < $l; $i++){
$obj = $array[$i];
echo "ARRAY1: ".$array;
echo "L: ".$l;
echo "ARRAY2: ".gettype($array);
$q = 'INSERT INTO dependencies SET projectID = "1", `from` = "'.$obj->{'From'}.'", to = "'.$obj->{'To'}.'", type = "'.$obj->{'Type'}.'", cls = "'.$obj->{'Cls'}.'", lag = "'.$obj{'Lag'}.'"';
Error is thrown from line $q = 'INSERT INTO... and the printed variables show that indeed my $array is an Array :
ARRAY1: ArrayL: 2ARRAY2: array . What am I doing wrong here ?
json_decode returns an object, unless you specify you want an array with the second optional argument:
json_decode(stripslashes($_POST['data']), true);
Some other useful advice:
Use var_dump for debugging purposes. It will help you understand the structure of any objects/arrays in your code.
You should not be accepting data through post and the using it in an SQL query without any sanitation, anyways. I highly recommend you fix that asap.
You're missing a -> in the last assignment:
$obj{'Lag'}
The simplest way is as Paul pointed out and I'd advise this one. But if you ever need to cast an array as an object use:
$newObject = (object) $oldArray;