php json decode with variables that contains dashes [duplicate] - php

This question already has answers here:
How do I access this object property with an illegal name?
(2 answers)
Closed 10 months ago.
{"general":{
"round-corner":"0",
"border-stroke":"2",
"background-color":"#ffffff"
}
}
I have this json string, I know that php variable names doesn't support dashes. So what to do in this case ?

When dealing with valid json you don't need to do anything special to use the result in php as long as you don't use extract().
Admiditly it looks cleaner to let json_decode return an array here as Jay Bhatt suggests but you are also free to use a normal object as return (which is an instance of stdclass).
The properties of the returned object can be nearly anything. You just need to use the property name as a php-string instead of a hardcoded literal.
$obj->{'a sentence with spaces and umlauts äüö is valid here'}
<?php
$json = <<<JSON
{"general":{
"round-corner":"0",
"border-stroke":"2",
"background-color äü??$%§":"#ffffff"
}
}
JSON;
$obj = json_decode($json);
$keyName = "round-corner";
var_dump($obj->general->{'round-corner'});
var_dump($obj->general->$keyName);
var_dump($obj->general->{'background-color äü??$%§'});
Result

You can use an array format like this. Hyphened keys will work.
<?php
$json = '{"general":{
"round-corner":"0",
"border-stroke":"2",
"background-color":"#ffffff"
}
}';
$array = json_decode($json, true);
echo $array['general']['border-stroke']; // prints 2
?>
Here's a demo

Related

Extracting data from multiple Nested Json using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
Here's the json
{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}
Here's my code
$json = json_decode($data);
foreach($json["result"] as $result){
foreach($result["files"] as $file){
echo $file["file_code"];
}
}
I want to extract all values from the "file_code". I got an error
Warning: Invalid argument supplied for foreach()
I was able get the VALUE of the first one using
echo $json->result->files[0]->file_code;
Is it possible to use a LOOP for the files[0]?
This line:
foreach($json["result"] as $result){
sees $json['result'] as an object, and so the next line tests for total_pages["files"], which doesn't exist.
Putting both foreach's together solves the problem:
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}';
$json = json_decode($data, true);
foreach($json["result"]["files"] as $file)
print $file["file_code"];
Teh playground
Alternatively, make the JSON result into an array, and use object property accessors instead of associative array bindings.
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":[{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}]}';
$json = json_decode($data);
foreach($json->result as $result){
foreach($result->files as $file){
echo $file->file_code;
}
}
Teh playground
I replicated your situation and it turns out that your JSON is invalid. You're missing a } at the end.
The reason for not getting an exception is because json_decode does not throw an error by default. You can make it do so by adding the JSON_THROW_ON_ERROR flag,
read the docs for more info.
This works perfect for me. If you have any thoughts please feel free to correct me.
$num = count($json->result->files);
echo $num;
for($i=0;$i<$num;$i++)
{
echo $json->result->files[$i]->file_code;
}

How can i Iterate through data returned in Ajax success? [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
How can I iterate to get id value? This is my array:
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
tried
<?php
foreach($faculty as $value)
{
echo $value['Id'];
}
?>
Gives an error
Use of undefined constant Id - assumed Id
This is a json which is basically a string, to be more precise the given json contains a list (currently 1 element):
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
You need to convert it to an array first:
$jsonValues = json_decode($json, true); //here you will have an array of users (1 now)
foreach($jsonValues as $faculty) //for each user do something
{
echo $faculty['Id'];
}
This is JSON format. First you have to decode it. Example:
$a = '[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]';
$dec = json_decode($a);
echo $dec[0]->Id;
Result: 216
Decoded you have an array, containing exactly one object. You have to access the object properties with -> then.
With JSON [] brackets means an array, while {} brackets mean objects. Learn more: https://en.wikipedia.org/wiki/JSON

How to access data from {string} [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
Some fields save data in the following way in one of my database field:
{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}
(* Don't know how it's called so i wrote string in the title)
How can i access data in particular for every "value".
One way could be to explode for every field but is there a better way to do this?
$ask_for_price_variable = [value from field];
if ($ask_for_price_variable == 'YES') {
// Do something
}
EDIT: As i said i did not know how it was called "JSON" so i could not search for it. Thank you all for the answers.
It is json data. You can access it using json_decode in php
$json = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($json,true);
$ask_for_price_variable = $data['ask_for_price_en-GB'];
Use json_decode
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
print_r(json_decode($str, true));
You need to study about JSON type and how to encode or decode to get the data.
try this
echo "<pre>";
print_r( json_decode('{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}'));
to view the result , click run or hit f9, here
try json_decode function
$str = '{"per_meter_en-GB":"TEST_FOR_TEST","roll_40_en-GB":"","ask_for_price_en-GB":"YES"}';
$data = json_decode($str, true);
print_r($data);
output:
Array ( [per_meter_en-GB] => TEST_FOR_TEST [roll_40_en-GB] => [ask_for_price_en-GB] => YES )
here you can access required value from $data array eg. echo $data['per_meter_en-GB']; will output TEST_FOR_TEST

PHP json_encode return rows as objects instead of arrays [duplicate]

This question already has answers here:
json_encode/json_decode - returns stdClass instead of Array in PHP
(7 answers)
Closed 9 years ago.
I am using json_encode() to encode array into json format. but it returning object instead of array. I want to return an array not an object.
any body have any idea?
Basically json_decode() will return two types of data.
1) Object
2) Associative array
By default, json_decode() returns object type value.
But, if you want value as an array format you must use TRUE as a second argument in json_decode().
e.g,
$decoded_value = json_decode($json_encoded_value, TRUE);
use this code for decoding your encode json data
$encode = $your_json_encoded_data
json_decode($encode, TRUE);
actually json_encode function in php will return a json formatted string.
and if you want to parse json formatted string back in php
then you should use json_decode.
json_decode function will return data two types.
object & associtavie array.
json_decode(); return type object
json_decode(, TRUE); return type associtative array
You should use json_decode with TRUE param like following example:
$array = array(1,2,3);
$encode = json_encode($array);
$decode = json_decode($encode, TRUE);
Now $decode is array, not object.

How to decode a json data array? [duplicate]

This question already has answers here:
json_decode to array
(12 answers)
Closed 11 months ago.
The json data object below is what's returned from a custom Google search API request. I need to extract each of the "url" elements and place them into an array (using PHP).
myArray = {url1, url2, url3, etc...}
How?
data = '{
"responseData":
{
"results":
[
{
//etc
}
]
}
Am I right that you have JSON string? Use json_decode to decode it. After that you can use
array_map(function($x){
return $x->url;
},$var->responceData->results);
(Requires PHP 5.3 for anonymous function, you can use no anonymous ones if use PHP5.2 or older)
For later versions:
function smth($x){
return $x->url;
}
array_map('smth',$var->responceData->results);
You can use json_decode to get an array corresponding to your JSON and then analyze it like you would do for a normal array.
You might want to read up on json_decode
Try using:
$myObject=json_decode($myJSONstring);
Here's the reference.
Then do:
$urlArray=array();
foreach($myObject->responseData->results as $myResult) {
foreach($myResult as $myAttribute => $myValue) {
$urlArray[] = $myValue;
}
}
$urlArray will be what you're looking for.

Categories