Like in Java when you iterate a list, it's real easy, it's like: while(BLAH.hasNext()) { }, so how do I do that in PHP when I have an array within an stdObject that I want to iterate through each and every item?
I keep getting Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 29
<?php
$apiUrl = 'https://api.quizlet.com/2.0/groups/44825?client_id=***BLOCKED FROM PUBLIC***&whitespace=1';
$curl = curl_init($apiUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($curl);
if ($json) {
$data = json_decode($json);
echo "<h1>Sets from \"{$data->name}\"</h1>";
foreach ($data->sets as $key => $val) {
echo "$key: $val\n";
}
echo "</ul>";
var_dump($data);
}
?>
You can/should use foreach to iterate over every element of an array.
$foo = new stdClass;
$foo->arr = array('1','7','heaven','eleven');
foreach ($foo->arr as $val)
{
if (is_object($val)) var_dump($val);
else echo $val;
}
Note the line I added to var_dump sub-objects. The error you were initially getting was that the elements of your sets array were also objects, not strings as expected. If you only need to access certain elements of the set objects, you can access them using $val->property.
For example you have an object like
$obj = new stdClass;
$obj->foo = 'bar';
$obj->arr = array('key' => 'val', ...);
$array = (array) $obj;
now you can use foreach to iterate over array.
foreach($array as $prop) {
//now if you are not sure if it's an array or not
if(is_array($prop)) {
foreach($prop as $val)
//do stuff
}
else {
//do something else
}
}
The $val variable holds another object (of type stdClass) which contains the details for an individual "set". As you can see, since it generates an error, you cannot echo a stdClass object.
You can access the values inside each object using the object->property notation that you seems to be getting familiar with. For example.
foreach ($data->sets as $set) {
echo $set->title . " by " . $set->created_by . "<br>";
}
/*
An example of the JSON object for a single $set
Access these like $set->title and $set->term_count
{
"id": 8694763,
"url": "http:\/\/quizlet.com\/8694763\/wh-test-1-2-flash-cards\/",
"title": "WH Test 1 & 2",
"created_by": "GrayA",
"term_count": 42,
"created_date": 1323821510,
"modified_date": 1323821510,
"has_images": false,
"subjects": [
"history"
],
"visibility": "public",
"editable": "groups",
}
*/
Related
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}
I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);
I have been trying to workout how to loop through and output the contents of a json file where field names start with "$" and keep getting an Undefined variable error message
Here is an example of the json file example (taken from https://mixpanel.com/help/reference/webhooks):
[
{
"$distinct_id":"13b20239a29335",
"$properties":{
"$region":"California",
"$email":"harry.q.bovik#andrew.cmu.edu",
"$last_name":"Bovik",
"$created":"2012-11-20T15:26:16",
"$country_code":"US",
"$first_name":"Harry",
"Referring Domain":"news.ycombinator.com",
"$city":"Los Angeles",
"Last Seen":"2012-11-20T15:26:17",
"Referring URL":"http://news.ycombinator.com/",
"$last_seen":"2012-11-20T15:26:19",
}
},
{
"$distinct_id":"13a00df8730412",
"$properties":{
"$region":"California",
"$email":"anna.lytics#mixpanel.com",
"$last_name":"Lytics",
"$created":"2012-11-20T15:25:38",
"$country_code":"US",
"$first_name":"Anna",
"Referring Domain":"www.quora.com",
"$city":"Mountain View",
"Last Seen":"2012-11-20T15:25:39",
"Referring URL":"http://www.quora.com/What-...",
"$last_seen":"2012-11-20T15:25:42",
}
}
]
I am testing with a static string just to try and get things working. Here is my test code...
<?php
$input = '[{"$distinct_id":"13b20239a29335","$properties":"dddd"}]';
$jsonObj = json_decode($input, true);
foreach ($jsonObj as $item) {
foreach ($item as $rec) {
echo '<br>';
$my_id = $rec->$distinct_id;
echo($my_id);
$my_id = $rec->$properties;
echo($my_id);
}
echo '<br>';
}
?>
Any help would be appreciated.
Noob!
UPDATE: Musa gave this example which works for the single level json:
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
$my_id = $item->{'$properties'};
echo($my_id);
echo '<br>';
}
How can this then be adapted to read and output all elements of the bigger multi-level json file?
Use Curly bracket notation
$object->{'$property'};
Edit
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
foreach ($item->{'$properties'} as $my_prop => $value){
echo("$my_prop => $value");
}
echo '<br>';
}
http://codepad.org/1cudZqlu
With the nested loop you're iterating the properties $distinct_id and $properties so $rec is actually a string and not an object.
Also your json is invalid as it has trailing , in the $properties field.
Apologies if this has been asked a thousand times, but I can't find a good tutorial on how to do this correctly and searching on Stack is coming up trumps.
I have a JSON file which has data like this:
{
"store":"Store 1",
"cat":"Categories",
"general_cat":"Categories",
"spec_cat":"Accessories"
},
{
"store":"Store 1",
"cat":"Categories",
"general_cat":"Categories",
"spec_cat":"Accessories"
},
with about 50 entries in it. I'm trying to parse this data and store the values in variables.
So far I've tried:
$string = file_get_contents("jsonFile.json");
$json_array = json_decode($string,true);
foreach ($json_array as $key => $value){
$store = $key -> store;
$general_cat = $key -> general_cat;
$spec_cat = $key -> spec_cat;
if (!is_null($key -> mainImg_select)){
$cat = $key -> cat;
}
echo $headURL;
}
This is resulting in "Trying to get property of non object" errors. What am I doing wrong here?
The second argument of json_decode tells the function whether to return the data as an object, or an array.
Object access uses the -> symbol. To return an object from json_decode either use json_decode($jsonString) or json_decode($jsonString, false) (the second argument is false by default)
$jsonString = '{ "this_is_json" : "hello!" }';
$obj = json_decode($jsonString);
echo $obj->this_is_json // "hello!";
You can also access your json data as an array by setting the second argument to true
$jsonString = '{ "this_is_json" : "hello!" }';
$arr = json_decode($jsonString, true);
echo $arr['this_is_json'] // "hello!";
What can be a little more conceptually confusing, is that PHP json_decode can return either an array of objects (rather than just an object), or an associative array.
Consider the following json string. This string represents a "collection" (square brackets) of json data structures (curly braces).
[
{
"name": "One"
},
{
"name": "Two"
}
]
If we assign this json to the variable $string hopefully this will illustrate the difference
$asObjects = json_decode($string);
$asAssociativeArray = json_decode($string, true);
foreach ($asObjects as $obj) {
echo $obj->name;
}
foreach ($asAssociativeArray as $arr) {
echo $arr['name'];
}
It seems like you are requesting an associative array (by passing True as the second parameter to the json_decode function) but trying to use it as an object.
Try $json_array = json_decode($string,false); . That will return objects
Also, as #MatRt mentions, you need to use $value instead of $key to reference the objects
You need to retrieve values with array syntax:
$item['key']
as apposed to
$item->key