JSON Decode - returning undefined index - php

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"

Related

How do I "trim" this JSON with PHP?

I have a JSON that's strangely formatted ...but it's the way I receive it. Because the arrays inside are huge, simply copying and pasting it takes a long time, so I'm wondering if there's a PHP way to do it.
The way I get it is like this:
{"count":459,"results":[{"title":"Something ....}],"params":{"limit..},"type":"Listing","pagination":{"..":5}}
But I want to get only the "results" array, basically the part of [{"title":"Something ....}]. How would I do that?
Do
$arr = json_decode(your_json, true);
If you ned it as JSON again, do
json_encode($arr['results']);
You can get to that part as follows:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit":".."},"type":"Listing","pagination":{"..":5}}';
$obj = json_decode($json);
echo $obj->results[0]->title;
Outputs:
Something ....
You have to decode your json. Be sure that the json is valid!
Your decoded json returns an object of type stdClass instead of an array!
See below the tested code:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit": "foo"},"type":"Listing","pagination":{"foo":5}}';
$decoded = json_decode($json);
So you can access array results from the object $decoded:
print_r($decoded->results);
But, in the array, there are objects, thus:
echo $decoded->results[0]->title; // Something ....

How to access complex JSON data in PHP

Here is the JSON response in which I need your help.
I need to access "age" key inside 'attribute'.
I really tried every possible ways that i could get. So can u please try to help me out :)
Another option, is that when you call json_decode by default you get a php object, however, if you add an optional boolean parameter you get an array which can be easier in situations like this to access nested elements.
// $data is the original json string
$json = json_decode($data, true);
print_r($json);
There are 2 ways I can see checking the json you just provided, one is by iterating the array, and the other one is accessing it by index:
$json = json_decode($response);
foreach ($json as $item) {
$value = $item->item->attribute->age->value;
var_dump($value);
}
the other way:
$value = $json[0]->item->attribute->age->value;

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.

Can't get value from array

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

Trouble looping through an array created from a foursquare JSON feed

I'm working on a side project and at its core, I need to get a foursquare json feed into an array that i can loop through. My code is below and results in the following error:
Warning: Invalid argument supplied for foreach() in /homepages/7/d346835943/htdocs/dealrub/results.php on line 56
Here is an example of the json feed that i am correctly acquiring:
$jsonurl = "http://api.foursquare.com/v2/venues/search?ll=".$lat.",".$lon."&limit=100";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_encode($json, true);
foreach ( $json_output->response->groups[0]->items as $items )
{
echo "{$items->name}\n";
}
Any help as to what i'm doing wrong would be greatly appreciated. I left the jsonurl without my api key, but it is successfully returning the json results.
You have to use json_decode.
Check whether $json_ouput is not empty.
You are passing true as second argument to json_decode (assuming you have it right) which means that it returns an associative array.
Either omit that:
$json_output = json_decode($json);
or access items as array:
foreach ( $json_output['response']['groups'][0]['items'] as $items )
You're using json_encode on a string that is already in json. Try json_decode instead ;)

Categories