What is the right way to access multidimensional json array in php? - php

I'm working on cookies that contain multidimensional JSON object array and I have bit of a problem accessing them. Kindly help me.
Here's a look at my problem:
I access the values from the html element and encode it before storing it into a variable,
var cookie_items = JSON.stringify({id: value, quantity: 1});
then I push this object into an array,
cookie_array.push(cookie_items);
finally, I push the cookie_array into another array with the associative name 'all',
final_cookie_array['all'] = cookie_array;
When I log final_cookie_array in the browser console, the output looks like this:
Object {all: Array[2]}
all: Array[2]
0: "{"id":"6","quantity":1}"
1: "{"id":"2","quantity":1}"
When I echo the cookie array in PHP, i.e., $_COOKIE['cookie_name']; it outputs the following:
[object Object]
But when I try echoing $_COOKIE['cookie_name']['all']; nothing gets displayed.
Can somebody please help me deal with this?
Thanks.

Try like example below
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$arr = json_decode($json,true);
var_dump($arr);
?>

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 ....

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"

json_decode() getting values

I am trying to get json data from the Statcounter API.
I have the following:
$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];
I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.
Here are the first couple lines of the unformatted json it is giving me.
This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.
http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514
{"#attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar
Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!
Thank you for your help.
Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:
echo $data['sc_data'][0]['log_visits'];
The code above will access the first element of the array sc_data and print the value of log_visits
When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].
The elements of the array can be any valid value, i.e.
string
number
object
array
true
false
null
In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")

How to write array for json encode to look like this

I am trying to get a specific json response, but one array in the response is being passed as an object.
"countries":{"TW":8,"JP":5,"AU":6,"MX":12,"CL":4,"HK":2,"US":14,"AR":4,"ES":1,"BR":1,"MY":9,"IT":12,"DE":1,"GB":1,"PE":6,"TR":1,"KR":3,"IE":1,"CA":2,"FR":1,"VE":2,"IL":1,"PT":1,"NL":1,"PL":1}
But I need it to look like this:
"countries":[["Brazil", 40.5],["US", 30],["Canada", 19.5], ["England", 10]]
How do I build that array in PHP for the json_encode response looks like that?
Now I have:
$countries['US']=14;
$countries['CL']=4;
....
Then I add that array ($countries) to the $data array, which is the one json encoded
$data['countries'] = $countries;
Which gives the result I posted first. But I need that in that in the second format.
Anyone knows what am I missing?
Thanks!
$countries = Array();
$countries[] = Array('Brazil', 40.5);
...

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