Looping through json_decode with foreach loop error - php

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!

Related

PHP looping over JSON objects in my database

I'm storing some values using the mysql json field type, in Sequel Pro I'm seeing them as follows
["feature1","feature2","feature3","feature4"]
In my PHP file, I can print out the contents using
echo $plan->features;
but what I want to do is look over each one so I can style them, but the problem is when I stick it in a foreach loop I get the following:
Invalid argument supplied for foreach()
My loop is straightforward
foreach ($plan->features as $features) {
}
I'm not sure I'm doing things right.
This is a JSON String
["feature1","feature2","feature3","feature4"]
User json_decode() for the above string
$string = json_decode($teststring,TRUE);
And after that you can for loop the variable or foreach the variable
foreach($string as $single_value)
{
echo $single_value.'<br>';
}
Output:
feature1
feature2
feature3
feature4

Merging to array and getting error

Here is what i am doing, Storing values from a form to array and then storing that array into a file (array.jason).
if (isset($_POST['addEntity'])) {
$values = array_values($_POST);
print_r($values);
unset($values[1]);
var_dump($values);
$file_values = json_decode(file_get_contents('array.json'), true);
array_combine($file_values,$values);
file_put_contents("array.json",json_encode($values),FILE_APPEND);
}
Now, when i try to merge array from file ($file_values) to an array which i get from submit ($values) i am getting this error or warning :(
Warning: array_combine() expects parameter 1 to be array, null given
in C:\Users\tej\PhpstormProjects\Final Year Project\index.php on
line 9
So there are a few things wrong in your code which got you a few errors. First I will show you how you can fix your code and second what went wrong and what happened.
So to fix your code you have to assign the return value of array_combine() back to $values and just overwrite the file, since you added the new data to the old decoded one, e.g.
if (isset($_POST['addEntity'])) {
$values = array_values($_POST);
unset($values[1]);
$file_values = json_decode(file_get_contents('array.json'), true);
$values = array_combine($file_values,$values);
file_put_contents("array.json", json_encode($values));
}
But what happened without that assignment and the appending of the file is. You just encoded your new data into JSON and appended it to your file. Means you created:
[DATA 1]
[DATA 2]
[DATA ...]
So when you tried to decode it again, all encoded data combined weren't valid anymore, even though they are as a single line they aren't as entire file. Which then lead json_decode() return NULL, since it wasn't valid JSON, and finally you tried to combine NULL with an array which got you a PHP error.

Read nested json in php

I know others have already asked about this, but I don't find a solution for my problem. In my PHP page I call an external service and I can't modify the response obtained.
I'm moving my first steps both with JSON and PHP.
The response is a JSON like this, I print this using the var_dump method:
object(stdClass)#1 (3)
{
["search_string"]=>string(15) "ABCDEFG HI LMNO"
["resut"]=>string(5) "apixi"
["0"]=>array(1){
[0]=>object(stdClass)#2(2){
["resp_code"]=>string(7) "12.34.0"
["resp_description"]=>string(15) "ABCDEFG HI LMNO"
}
}
}
In my PHP page I can read the value ”ABCDEFG HI LMNO” for the key "search_string" with this code, in the $output variable I store the result of the cUrl call
.......
$output = curl_exec($ch);
$jsonDecode =json_decode(str_replace('""','"',$output));
var_dump($jsonDecode);
echo $jsonDecode -> search_string;
I need the str_replace method because the JSON is dirty but not always, how can I access at the fields "resp_code" and "resp_description" and then store them in a variable? I tried many solutions but none works for me.
Instead of converting JSON array to stdClass object you can also convert it to regular PHP array by adding second parameter to the json_decode function:
$jsonDecode =json_decode(str_replace('""','"',$output), true);
In your case in the output, you'll get a multidimensional array.
Then, to access resp_code and resp_description, you can do something like this:
$respCode = $jsonDecode[0]["resp_code"];
$respDescription = $jsonDecode[0]["resp_description"];
In the decoded JSON you have, the resp_code and resp_description keys are difficult to get to, because the top-level object has a numerical ("0") attribute. Trying to reach that attribute like this:
$jsonDecode -> 0
will give this parsing error:
syntax error, unexpected '0' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
Trying the same with a string notation (-> "0") also fails.
However, the suggestion in the error message is useful: encapsulate the zero with braces. Then you can proceed easily by adding the array index selector ([0]) to get to the object and keys of your interest, like this:
echo $jsonDecode->{0}[0]->resp_code;
echo $jsonDecode->{0}[0]->resp_description;
If you expect more elements in that array $jsonDecode->{0}, then loop over them like this:
foreach ($jsonDecode->{0} as $element) {
echo $element->resp_code;
echo $element->resp_description;
}
Alternative
If, however, you prefer to work with associative arrays instead of objects, you can use the second argument of json_encode as stated in the docs:
assoc
When TRUE, returned objects will be converted into associative arrays.
So then you would pass true as second argument:
$jsonDecode = json_decode(str_replace('""', '"', $output), true);
The above code would then be rewritten like this to access the variable as an associative array:
foreach ($jsonDecode[0] as $element) {
echo $element["resp_code"];
echo $element["resp_description"];
}

Access JSON values in PHP

{"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.

getting a value of a known key in php failing

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.

Categories