PHP looping over JSON objects in my database - php

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

Related

How can I foreach over this piece of json

Im trying to iterate over the file https://alexa.rob-balmbra.co.uk/tracker/mapping.json
Im trying to loop over each name as in "4-72", however i want access to its contents and its name.
Im doing a search in its content and when I have matched the code, I need to subsequently get the key as in '4-72', etc...
Every time I use foreach i get the contents of the json file rather than the key and the contents.
//Fetch the JSON file and decode it into an associative array
$json = json_decode( file_get_contents('https://alexa.rob-balmbra.co.uk/tracker/mapping.json'), true );
//This is the code you want to search for
$searchCode = "03013";
//Loop through the json array, get key and data
foreach($json as $key=>$data){
//If the code matches what you're searching for, echo the key out and move past the foreach loop.
if($data["code"] == $searchCode){
echo "The service name is: " . $key;
break;
}
}
//You don't need this here. I just used it so I could see all the codes.
echo '<pre>' . print_r($json, 1) . '</pre>';
The code explained:
Go and get the JSON file from the web page
Decode the JSON file into an associative array so PHP can work on it
Set up a search code
For all the keys, search each code to see if it matches the search code
If there is a match, Show the respective key.
Every time I use foreach i get the contents of the json file rather than the key and the contents.
Have you turned the JSON string into an array?
$jsonValues = json_decode($jsonString,true) ;
foreach($jsonValues as $key=>$data) {
// do your thing here
}

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"];
}

Query and decode json form mysql database

I have this JSON encoded code in my mysql database:
{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}
And i want to query and decode it to echo it at my website.
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}';
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
/ just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key <br/>";
foreach($value as $k=>$data)
{
echo "$k | $data <br/>";
}
}

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 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!

How to create an array from multiple arrays in a mysqli fetch loop

I am trying to create an array so i can print it in json format. I am querying a database using mysqli so and in the fetch loop sticking the returned information in an array, and trying to stick all of the arrays returned into one array and print that array in json format, but i cant seem to do it. here is my code, any help or insight would be vastly appreciated.
while($stmt->fetch())
{
$array .= ("title"=>$title,"date"=>$date,"body"=>$body)
}
print_r(json_encode($array));
but what is printed is
ArrayArrayArrayArrayArray
can anyone please help?
Use the [] syntax to append a new element onto your array $array
$array = array();
while($stmt->fetch())
{
$array[] = array("title"=>$title, "date"=>$date, "body"=>$body);
}
print_r(json_encode($array));
Edited. Originally missed that this used MySQLi bound variables, rather than a fetched row.

Categories