简体   繁体   中英

Looping through json_decode with foreach loop 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 be foreach($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 eg 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM