PHP problems wiith decoding JSON - php

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;

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.

PHP ArrayUndefinedOffset But Why?

I have dataset like the following, one of my table column let say prices column store prices in json format, example given below.
<?php
$dataSet[] = array(
"product_id" => 1,
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesStdClassObject = json_decode($dataRow['prices']);
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;
print_r($pricesArray);
}
?>
The output of print_r($pricesArray) is the following
Array ( [1] => 29990 [2] => 10000 )
Then why print_r($pricesArray[1]) give me error
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
But why?
And finally i found the solution:
According to the documentation here and from the forum here I found a ‘assoc’ parameter of json_decoded method that used with this method and by default its value is FLASE, json_decoded return stdClass objects if you want the returned objects converted into associative arrays then you have to make the ‘assoc’ parameter value to TRUE like the following.
$pricesStdClassObject = json_decode($dataRow['prices'], TRUE);
So the above example code will become like this
<?php
$dataSet[] = array(
"prices" => '{"1":"29990", "2": "10000"}'
);
foreach ($dataSet as $dataRow)
{
$pricesArray = json_decode($dataRow['prices'], TRUE);
// returned objects will be converted into associative arrays.
print_r($pricesArray);
}
?>
And then you can access the indexed value with no error message :)
print_r($pricesArray[1]); output: 29990
Array type casting with json decoded StdClass Objects is not working properly, you can skip the following piece of code if you are using the ‘assoc’ parameter.
// Convert stdClass Object into array
$pricesArray = (array) $pricesStdClassObject;

how do I get my php array to json

I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);

How can I fix this error about stdClass in 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

how to convert multidimensional array to object in php?

i have a multidimensional array:
$image_path = array('sm'=>$sm,'lg'=>$lg,'secondary'=>$sec_image);
witch looks like this:
[_media_path:protected] => Array
(
[main_thumb] => http://example.com/e4150.jpg
[main_large] => http://example.com/e4150.jpg
[secondary] => Array
(
[0] => http://example.com/e4150.jpg
[1] => http://example.com/e4150.jpg
[2] => http://example.com/e9243.jpg
[3] => http://example.com/e9244.jpg
)
)
and i would like to convert it into an object and retain the key names.
Any ideas?
Thanks
edit: $obj = (object)$image_path; doesn't seem to work. i need a different way of looping through the array and creating a object
A quick way to do this is:
$obj = json_decode(json_encode($array));
Explanation
json_encode($array) will convert the entire multi-dimensional array to a JSON string. (php.net/json_encode)
json_decode($string) will convert the JSON string to a stdClass object. If you pass in TRUE as a second argument to json_decode, you'll get an associative array back. (php.net/json_decode)
I don't think the performance here vs recursively going through the array and converting everything is very noticeable, although I'd like to see some benchmarks of this. It works, and it's not going to go away.
The best way would be to manage your data structure as an object from the start if you have the ability:
$a = (object) array( ... ); $a->prop = $value; //and so on
But the quickest way would be the approach supplied by #CharlieS, using json_decode(json_encode($a)).
You could also run the array through a recursive function to accomplish the same. I have not benchmarked this against the json approach but:
function convert_array_to_obj_recursive($a) {
if (is_array($a) ) {
foreach($a as $k => $v) {
if (is_integer($k)) {
// only need this if you want to keep the array indexes separate
// from the object notation: eg. $o->{1}
$a['index'][$k] = convert_array_to_obj_recursive($v);
}
else {
$a[$k] = convert_array_to_obj_recursive($v);
}
}
return (object) $a;
}
// else maintain the type of $a
return $a;
}
Hope that helps.
EDIT: json_encode + json_decode will create an object as desired. But, if the array was numerical or mixed indexes (eg. array('a', 'b', 'foo'=>'bar') ), you will not be able to reference the numerical indexes with object notation (eg. $o->1 or $o[1]). the above function places all the numerical indexes into the 'index' property, which is itself a numerical array. so, you would then be able to do $o->index[1]. This keeps the distinction of a converted array from a created object and leaves the option to merge objects that may have numerical properties.

Categories