reading json encoded php array using ajax request - php

I have a php array with key, value pairs. I have json encoded it. And using ajax.Request i called the php file in which that array is there. Now i have to access both key and value pairs. Could anyone let me know how to do that?

You need to parse the JSON.
You can use the JSON library.
You can use a library method like jQuery's $.parseJSON().
If the JSON is trusted, you can use eval().

Code in javascript "json.js" is required. you can download this.
var votedCommentString = getCookie("votedComment"); // get value of voted comment cookie
votedComment = JSON.parse(votedCommentString); // extract json object into array
votedComment[votedComment.length] = id; // add more data in array
var cookieData = JSON.stringify(votedComment); // convert array into json object
setCookie("votedComment", cookieData, 365); // and again set cookie
In PHP you can access this in following way
$cookieData = (array)json_decode($_COOKIE["votedComment"]); // extract json object into array
print_r($cookieData);
Use
json_encode($array_variable) // to convert array in to json

As you said the array is in php file which is called via ajax, you can simply decode the json encoded string and retrieve the array with keys and values respectively.
Simply use json_decode() function to retrieve the array.

Related

CakePHP hash extract from JSON data

I am trying to extract some part of a JSON formatted string in CakePHP using the Hash::extract method .
Here is the JSON string:
[[{"name":"Atkins Global","y":{"count":96,"type":"1"}},
{"name":"HFT","y":{"count":444,"type":"1"}},
{"name":"Catalyst","y":{"count":8,"type":"1"}},
{"name":"BGL","y":{"count":2,"type":"1"}}]]
Here is what I used in CakePHP to retrieve the above JSON:
debug(json_encode(Hash::extract($data['type'], '{s}')));
$data['type'] holds the data above.
Is there a way I can grab the type values only? Not sure how I can do this in CakePHP. Would appreciate if anyone can help.
From an answer by Roberto Atkinson, you have to do json_decode() first to convert a JSON string to a PHP array, instead of encoding an array to JSON. Reference: json_decode()
In your case, try:
//from JSON string to PHP array; force returned objects to be converted into associative arrays
$data['type'] = json_decode($data['type'], true);
//now you can extract type values from data
$output = Hash::extract($data['type'], '{s}'));
In addition, according to CakePHP official API documentation: Hash::extract(), the first parameter should be an array.
Parameters (array|ArrayAccess $data The data to extract from., string $path The path to extract.)

How I can retrieve the length of a part of json object using PHP?

I have retrieved a PHP variable session that contains a JSON object. The JSON object is the following:
var jsonObject = {
"menu":{
"intro":{
"intosub":"sub_1"
},
"vis":{
"visub":"sub_2"
}
}
};
How can I know the length of a part of this JSON object? That is, I want to know how much elements that contain the key Intro and the same with key vis.
I have reviewed some post about this issue, and I found that I have to change the structure of JSON object, but this is not possible. Is there any other way in order to do this?
First, parse json to php associative array, use json_decode(your_var, true) . You will get a multidimensional array. Then use php count function on desired subarray

PHP display array in array in array

I want know how to access to array in array in array in php.
The result with $user is this:
'pages':{'x','y','z','access':{'a':3,'b':6,'c':8,'contact':2}}
How I can access to contact, please?
First of all this is JSON (probably), so before we can access it with php we need to decode it using json_decode which will give you a php object. (i made it valid JSON)
$jsonString = '{"pages":{"x": 0,"y": 0,"z": 0,"access":{"a":3,"b":6,"c":8,"contact":2}}}';
$phpObject = json_decode($jsonString);
var_dump($phpObject->pages->access->contact);
// prints int(2)
Use json_decode to convert this to array in PHP (if it is JSON)
It seems your string missing {} around.
{
"id":1,"active":1,"canAccess":{"entities":{"1":{"name":"blablabla","services":{"‌​45":{"name":"xxx"}}}}},"blabla":null,"pages":{"acces":{"notifications":1,"contact‌​":2}}
}
then it is a valid JSON string.
var_dump(json_decode($string,true));

pass multidimentional array from javascript to php

Im running a javascript code which reads values from different XML files and it generates a multidimentional array based on those values. Now I need to pass this array to a PHP page. I tried different but it always pass the arrray as string not as an array.
Anyone has an idea :( ... and thank you very much
What Caleb said.
Use this and JSON encode your JS array to a string, send it over to PHP and use json_decode to decode it into a PHP array.
You need a JSON encoder/decoder to do that. Prototype has it implemented by default and with jQuery you can use jQuery-JSON
For example if you use Prototype as your JS library then you can convert your array into a string like that:
var example_multi_dim_arr = {"a":[1,2,3], "b": [4,5,6]};
var string_to_be_sent_to_server = Object.toJSON(example_multi_dim_arr);
And in the PHP side (assuming that the JSON string is passed to the script as a POST variable)
$multi_dim_arr = json_decode($_POST["variable_with_json"], true);
The last true field in json_decode indicates that the output should be in the form of an array ($multi_dim_arr["a"]) and not as an object ($multi_dim_arr->a).
NB! the function json_decode is not natively available in PHP 4, you should find a corresponding JSON class if you are using older versions of PHP. In PHP 5 everything should work fine.

Best way to pass JSON from Browser to PHP using Ajax.Request

Hi I have a JSON object that is a 2-dimentional array and I need to pass it to PHP using Ajax.Request (only way I know how). ...Right now I manually serialized my array using a js function...and get the data in this format: s[]=1&d[]=3&[]=4 etc. ....
my question is: Is there a way to pass the JSON object more directly/efficientely?..instead of serializing it myself?
Thanks for any suggestions,
Andrew
You can also use Prototype's function toJSON() to convert an array into a JSON object. After passing it to server via Ajax call, simply use PHP's function json_decode() to decode the object.
Pass the object as a JSON-string to PHP, and in PHP use the builtin json_decode to get a PHP-object from the string.
In Javascript, use a "stringify" function on your object to get it as a string, library available for example here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
In que Javascript side (with Prototye):
var myJSON= Object.toJSON(youArray);
In que Php side:
$myjson = $_POST['myjson'];
$arrayJSON= json_decode(stripslashes($myjson), true);
Check
http://www.openjs.com/scripts/data/ued_url_encoded_data/
to encode nested data directly correct, since Object.toQueryString() doesn't accept nested data...

Categories