loop through JSON string in php - php

I have a json string derived from MySQL query using GROUP_CONCAT (which returns STRING).
Here's JSON string as field portfolios:
[
{name:"Branch GBD_1.pdf", img_path:"1333752771.pdf"},
{name:"Doc.pdf", img_path:"2020107119.pdf"},
{name:"COK.pdf", img_path:"264860069.pdf"}
]
Now in php, I tried to decode the field and loop through it, but I am not being able to.
foreach($records as $r)
{
$varArray = json_decode($r['portfolios'], true);
foreach($varArray as $que)
{
echo $que['name'].' '.$que['img_path'];
echo '<br/>';
}
}
How do I break or convert the variable into loop-able object?

$varArray is not an array because your json string is not valid json. The keys need to be wrapped in doublequotes.
[
{"name":"Branch GBD_1.pdf", "img_path":"1333752771.pdf"},
{"name":"Doc.pdf", "img_path":"2020107119.pdf"},
{"name":"COK.pdf", "img_path":"264860069.pdf"}
]

Related

PHP delete json array item messes up the JSON itself

I am facing a strange issue with my PHP code (I'm a beginner to PHP so apologies for my bad coding skills). Each array item in my JSON has a unique ID associated with it, to delete an array I just pass the unique ID to my code and it deletes the array item associated with it, but all my array items contain an integer field and that doesn't get deleted and it messes up my JSON (parsing fails when I try to do so later).
<?php
$var1 = filter_input(INPUT_POST, 'unique_id', FILTER_UNSAFE_RAW);
if ($var1 === null) {
die('The "unique_id" parameter is not set');
}
$data = file_get_contents('feed.json');
if ($data === false) {
die('An error occurred when opening "feed.json"');
}
$json = json_decode($data, true);
if ( ! isset($json[0]['unique_id'])) {
die("The JSON was not decoded correctly");
}
foreach ($json as $key => $value) {
if ($value['unique_id'] == $var1) {
unset($json[$key]);
}
}
$new_json_string = json_encode($json);
file_put_contents('feed.json', $new_json_string, JSON_UNESCAPED_SLASHES | LOCK_EX);
echo "Success";
?>
Here's the sample JSON:
[
{"student_id":"22222222","unique_id":"862916786a1340afbfdf23caa541963f","status":"Hey yo what's up","image":"none","likes":"0"},
{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"none","likes":22}
]
after deleting, I'm left with
{"1":{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"","likes":31}
As you can see {"1": is invalid and shouldn't be there.
Does anyone know what am I doing wrong?
EDIT: Here's my code to create a new array item in my JSON
$json = file_get_contents('feed.json');
$data = json_decode($json);
$data[] = array('student_id' => "$student_id", 'unique_id' => "$unique_id" ,'status' => "$status_txt", 'image' => "$image_link", 'likes' => "0");
file_put_contents('feed.json', json_encode($data), JSON_UNESCAPED_SLASHES | LOCK_EX);
This is a combination of two things:
There is no representation of sparse Arrays in JSON
JSON's arrays with [] can only have a comma-separated list of contiguous elements starting from index 0.
No type information distinguishes JSON arrays and JSON objects in PHP
Both of these things are stored as PHP's array type. JSON objects use the associative keys.
When you unset index 0 from your array, it becomes sparse. Now, the only way to encode something that has a something[1] but no something[0] in JSON is to have an object with a key "1".
PHP's JSON encoder allows this because the array you pass in is of the right type (array) to be serialized as a JSON object. So it does this.
Maybe you wanted to use array_splice to remove the array element instead of unset.
Use array_values() to convert array as notified by Cheery in comments.

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

Get the value for key in json array in php

How to get the corresponding value for key associated
[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]
Your Json is valid. You can validate at following
website: http://jsonlint.com/
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 = '[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]' ;
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.
$json_decoded_data = json_decode($json_string, true);
// 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 $key2 => $value2) {
echo "$key2 = $value2 <br />";
}
}
Output :
0
name = challenge
properties = Array
1
name = challenge
properties = Array

Get JSON data type from associative array in PHP

Evening everyone!
So, I have with me a JSON string...
{"username":"87db3983285d395ca0af9f","password":"f4f0bb1533ef5034ce6b0a8a7c49a43b","email":"xxx#gmail.com","hnum":3,"splicenum":22,"reg_ip":"71.126.122.217","reg_date":1364175245,"cur_ip":"71.126.122.217","ip_array":["71.126.122.217"],"logins":[],"about":""}
And I decode this string into an associative array in PHP using json_decode().
What I'm doing is trying to make 1 single function for querying a JSON object that has been converted to an associative array in PHP. For this function, I am now working on editing/updating fields.
Example:
json_edit(array(
"set"=>array(
"email"=>"yyy#yahoo.com"
)
));
The key "set" means setting the value of a string or boolean.
Another key would be "push" to append to an array, or "delete" to delete a string or an array.
What I'm wondering is, how can I get the data type of the current array part in PHP?
Meaning, how can I get PHP to say, "OK, the field 'username' is a string, and 'ip_array' is an array"?
I don't want to be able to "set" a string value to what is SUPPOSED to be just a boolean, or, an array.
Is there any way to get the JSON data types in PHP?
Thanks so much in advance.
What about gettype(). Gettype() will return the data type of any variable. http://php.net/manual/en/function.gettype.php
I would use something like this;
<?php
function json_edit($json, $changes = array()){
$decoded = json_decode($json);
foreach($changes as $action => $data){
swith($action){
case 'SET':
foreach($data as $key => $value){
$decoded[$key] = $value;
}
break;
case 'DELETE' :
break;
default;
}
}
return json_encode($decoded);
}
?>

How to get individual fields from JSON in PHP

My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.

Categories