vitto vitto - 25 days ago 9
PHP Question

PHP: parse JSON from jQuery

I'm trying to parse a simple

JSON
string, but I'm not used to do it from
PHP
. To do my test I've written a page where the data is created; sends request to PHP page to do some tests.

How can I access the JSON data from PHP and have it returned back?

The string from jQuery:

var json_str = '{"id_list":[{"id":"2","checked":"true"},{"id":"1","checked":"false"}]}';
/*'{
"id_list": [
{
"id": "2",
"checked": "true"
},{
"id": "1",
"checked": "false"
}
]
}'*/
$.post ("php_json_parser.php", { data_to_send:json_str }, function (data_back) {
alert (data_back);
});


PHP page:

<?php

$data_back = json_decode (stripslashes($_REQUEST['data_to_send']), true);
print $data_back->{'id_list'[0]["id"]}; //??? how can I access to properties?

?>

Answer

json_decode with the second parameter set to true turns the JSON item into a php array.

So to access the element in your example, you'de use

$data_back['id_list'][0]['id']