How can I fix this error about stdClass in PHP - php

This is my code:
$array = array(
"Birds" =>
array(
'group' => 1,
"Bird" => array(
array('id' => 1, 'img' => "img1.png", 'title' => "kate"),
array('id' => 2, 'img2' => "img2.png", 'title' => "mary")
)) );
$json = json_encode($array);
echo json_decode($json);
OUTPUT IS:
//JSON OUTPUT {"Birds":{"group":1,"Bird":[{"id":1,"img":"img1.png","title":"cardinal"},{"id":2,"img2":"img2.png","title":"bluejay"}]}}
Object of class stdClass could not be converted to string

try
var_dump($json);
This allows you to print out the details of objects and other non-primative types.
Echoing is used for strings - Your json decoded string will be an object of type stdClass
See var_dump http://php.net/manual/en/function.var-dump.php
See echo http://php.net/manual/en/function.echo.php

You have to pass the second parameter of json_decode as true, more info about these parameters at: http://php.net/manual/en/function.json-decode.php
so your echo json_decode($json); should be changed to this:
print_r(json_decode($json, true));
echo is changed to print_r since the output is an array not a string ...

Use var_dump to view variables echo converts your variable to string, while it's object. Also you can add second param to json_decode($data, true) to get array instead object, as i assume that's what you want, because input is array.
About object convertion to string you can read __toString

Related

Cannot iterate over array after json_decode(file_get_contents(filename))

I want to write an Array as JSON into a file. Then i want to get the content, decode it and iterate over the array. The Problem is i cannot iterate over the Array that i get from the file. What am i doing wrong?
var_dump() shows the array.
<?php
$array = array(
array("Artikel" => "Bananen",
"Menge" => 10,
"id" => "4711"
),
array("Artikel" => "Eier",
"Menge" => 1,
"id" => "abc"
)
);
file_put_contents("daten.json", json_encode($array));
$array1 = json_decode(file_get_contents("daten.json"));
var_dump($array1);
for($i=0; $i<count($array1); $i++){
echo $array1[$i]["Menge"];
echo "<br>";
}
?>
If you run your code, you will get the error Cannot use object of type stdClass as array.
This is because when json_encode is executed, the nested arrays are interpreted as an objects.
If you write:
$array1 = json_decode(file_get_contents("daten.json"), true);
then the objects will be converted to arrays and everything will work as expected.

Parse string to array like CakePHP form data

I am looking for a way to parse strings in an array to an array which has a similar pattern to how CakePHP handles POST data. Or even a function in CakePHP that would do it.
UPDATED:
Current array:
array(
'data[callers]' => (int) 4,
'data[status]' => 'Unknown',
'data[country_id][107]' => (int) 1,
'data[country_id][150]' => (int) 0
)
Desired result:
array(
'callers' => (int) 4,
'status' => 'Unknown',
'country_id' => array(
(int) 107 => (int) 1,
(int) 150 => (int) 0
)
)
The purpose is saving serialized form data which can later be passed to a PHP function without having to POST the data from the browser.
The data comes from a form which was serialized and saved in the database. CakePHP generates input names in the form with brackets like this: data[country_id][107] and inside the controller you can access it like this $this->request->data['country_id']['107']
But when I serialize the form with javascript and save the raw JSON string in the database I need a way to make it into an array like CakePHP does.
Firstly make sure your array is valid first like:
$data = array (
'callers' => 4,
'status' => 'Unknown',
'country_id' => array(
'107' => 0,
'150' => 0
)
);
JSON ENCODE
Now you can json encode it
$json = json_encode($data);
echo $json; // prints: {"callers":4,"status":"Unknown","country_id":{"107":0,"150":0}}
See ^ it is now a string.
http://php.net/manual/en/function.json-encode.php
JSON DECODE
Then when you need it as an array call json_decode()
json_decode($data, true);
Note the second parameter is setting return array to true else you will get an the json returned as an object.
http://php.net/manual/en/function.json-decode.php

Getting a value from associative arrays PHP

I have an array..
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
)
and I am trying to extract the name using
$fileName = $file['meta'['name'];
which gives me a Illegal string offset 'name' error.
The value of $file['meta'] is a string, not an array. That means your approach to access the value does not work.
It looks like that meta value string is a json encoded object. If so you can decode it and then access the property "name" of the resulting object.
Take a look at this example:
<?php
$file = [
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => []
];
$fileMeta = json_decode($file['meta']);
var_dump($fileMeta->name);
The output obviously is:
string(12) "IMAG0161.jpg"
In newer version of PHP you can simplify this: you do not have to store the decoded object in an explicit variable but can directly access the property:
json_decode($file['meta'])->name
The output of this obviously is the same as above.
This is happening because your meta is a json, so you should decode and then access whatever you need, not that I placed true as second parameter becuase i wanted to decode as an associative array instead of an object
$decoded = json_decode($file['meta'],true);
echo $decoded['name'];
//print IMAG0161.jpg
You can check a live demo here
But you can easily access as an obect
$decoded = json_decode($file['meta']);
echo $decoded->name;
//print IMAG0161.jpg
You can check a live demo here
<?php
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
);
$meta=$file['meta'];
$json=json_decode($meta);
echo $json->name;
?>

Confusion with JSON_DECODE second param

I just created a small program to check JSON and JSON_FORCE_OBJECT
$tree = [
0 => array
(
'id' => 1,
'parent' => '0',
'name' => 'b',
'surname' => 'myfolder/b'
),
1 => array
(
'id' => 2,
'parent' => 1,
'name' => 'ignore',
'surname' => 'myfolder/ignore2'
),
2 => array
(
'id' => 3,
'parent' => 1,
'name' => 'ignore2',
'surname' => 'myfolder/ignore4'
)
];
var_dump($tree);
$try = json_encode($tree);//To print with key. Also if we decode we get result as object
//echo $try;
echo '<br />';
$try2 = json_decode($try,JSON_FORCE_OBJECT);
var_dump($try2);
$try2 is exactly equal to $tree an associative array.
Whereas if I remove JSON_FORCE_OBJECT from this line
$try2 = json_decode($try,JSON_FORCE_OBJECT);
I get an array with child object. Though JSON_FORCE_OBJECT is supposed to be used with json_encode but using it with json_decode, I get a surprising result. I am unable to understand whats going on inside?? I thought when I encode it and decode it I should get same result. But I got the same result only when I used JSON_FORCE_OBJECT. Can anyone please help why this happens?
According to the manual: http://php.net/manual/en/function.json-decode.php
json_decode returns an array of objects if you want to convert them in assoc array you should specify the second param which is a boolean
JSON_FORCE_OBJECT is an int with value 16...
when this is passed as second param php cast/converts it to its bool equivalent which true.
To test the above stated behavior try:
var_dump((bool)1; (bool)2, (bool)16)
//output bool(true) bool(true) bool(true) .
var_dump((bool)0)
//outputs bool(false)
So it's nothing to do with JSON_FORCE_OBJECT...even
json_decode($try,true);
json_decode($try,2);
json_decode($try,3);
json_decode($try,4);
json_decode($try,'someVar');
....
//should return your expected result (assoc array)
Similarly if you pass 0 as second param PHP will cast it into bool (which is false) and returns you an object
json_decode($try,0);
json_decode($try,false);
json_decode($try,null)
json_decode($try)
...
//will return objects
The second parameter to json_decode is a boolean. It accepts true or false. It does not accept JSON_FORCE_OBJECT. You're trying to use the wrong constant for the wrong function.
json_decode's 4th parameter accepts a bitmask of constants, but currently it only supports JSON_BIGINT_AS_STRING.
If you want to return stdClass instances for JSON objects from json_decode, set its second parameter to false (the default). Setting it to any non-falsey value makes it return associative arrays instead of objects. Setting it to JSON_FORCE_OBJECT counts as "not-falsey".
It's all described in the manual: http://php.net/json_decode

PHP problems wiith decoding JSON

I have this data:
Array
(
[id] => 19936953
[name] => Zackaze
[profileIconId] => 585
[summonerLevel] => 30
[revisionDate] => 1394975422000
)
$str = json_decode($data,true);
$row = (object) $str;
echo $row['name'];
I tried this code but it constantly gives this error:
Fatal error: Cannot use object of type stdClass as array
Hopefully you can help me.
While the conversion to an object is unnecessary (as others have mentioned), that is not the cause of your error. You cannot access object properties using $array['key'] notation. You must use $object->property.
Alternatively, you can remove the $row = (object) $str; line, and then you can access $row as an array.
You already have decoded your json as an associative array since you used true as second parameter so you can print it directly with scopes. If you need to decode as an object simply remove the second parameter, I think you will need to access it in another way though.
$str = json_decode($data,true);
echo $str['name'];
The second argument of json_decode will convert the Object into a Associative Array. Just remove the second argument or change it to false and it will return a stdClass instead of a Associative array.
You can see the Documentation.
Try outputting like
$str = json_decode($data,true);
$str = array
(
'id' => 19936953,
'name' => Zackaze,
'profileIconId' => 585,
'summonerLevel' => 30,
'revisionDate' => 1394975422000
);
$row = (object) $str;
echo $row->name;
Or a cleaner way
$str = json_decode($data);
echo $str->name;

Categories