Can't get value from array - php

I'm trying to output the value of the email value of an array, but have problems doing so.
The array is based on json_decode()
This is the error I receive
Fatal error: Cannot use object of type stdClass as array in /home/.... line 57
JSON (value of: $this->bck_content)
{"email":"test#email.com","membership_id":"0","fname":"Kenneth","lname":"Poulsen","userlevel":"1","created":"2012-04-23 10:57:45","lastlogin":"2012-04-23 10:58:52","active":"y"}
My code
# Display requested user details
$details_array = json_decode($this->bck_content);
$value = $details_array['email'];
print $value;

You need to use the second argument to json_decode to force array structures on JS objects.
json_decode($this->bck_content, true);
This will make sure all JS objects in the json are decoded as associative arrays instead of PHP StdObjects.
Of course that is assuming you want to use array notation to access them. If you're fine with using object notation then you can just use:
$value = $details_array->email;

try this one
$value = $details_array->email;
or
json_decode($json, true);
or
$details_array = (array)json_decode($json);
what have you done wrong is writen in error description

Related

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

JSON Decode - returning undefined index

Am trying to get more familiar with JSON decoding, so here's what I got:
$json = '{"id":[{"tier": "SILVER"}]}';
$array = json_decode($json, true);
var_dump($array["id"]['tier']);
I am trying to fetch the 'tier', but it's resulting the following error: Notice: Undefined index: tier
I have tried certain things such as var_dump($array['tier']);, var_dump($array[0]['tier']); but nothing seems to work and I can not find a lot of information about this.
After the Noticeit also returns NULL. Any help is appreciated.
The id key in the resulting array will contain an numerically indexed array of arrays.
To access, you need to specify the key in that array, in this case 0 as there is only a single element
var_dump($array["id"][0]['tier']);
If you where to decode to an object rather than forcing an associate array (by omitting the true in the json_decode call), you might find the syntax a little easier to read:
$json = '{"id":[{"tier": "SILVER"}]}';
$obj = json_decode($json);
var_dump($obj->id[0]->tier);
You need to access the first item [0]on the array ["id"]
Try this:
$json = '{"id":[{"tier": "SILVER"}]}';
$array = json_decode($json, true);
var_dump($array["id"][0]['tier']);
//string(6) "SILVER"

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
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 = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
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 | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

Print value from PHP key value pair

I have a key/value pair passed from Javascript via $.post as data : user_id.
I've brought it into PHP with $data = $_POST['data'] and when I vardump() that I get {"id":"1"}" as expected. However, I'd like to just access the value of 1.
How would I do that?
It's just JSON. Use json_decode() to turn it into an object (or an array if you so choose) and then get the value of ID using standard object member variable access methods:
$data = json_decode($_POST['data']);
echo $data->id;
Demo
If you're using PHP 5.4+ (using array syntax and array dereferencing):
echo json_decode('{"id":"1"}', true)['id'];
Demo
You can also try this:
$data = json_decode($_POST['data'], true)['id']

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.

Categories