简体   繁体   中英

Json Object to PHP array - not converting

I am trying to take a json object stored in a textarea and convert it into a php array. I assign the value of the textarea to variable like $data = $_POST['data'] . When I submit the value of the text I use json_decode($data, true) to convert from JSON Object to php array. But nothing happens. It seems like nothing is assigned. How can I achieve the above?

EDIT: I have added quotes and made the suggestion below and is not working: DEMO

PHP

if(isset($_POST['submit'])) {
$data = $_POST['data'];
$personArray = json_decode($data, true);
print_r($personArray);
}

HTML

<textarea name="data">[{
    "firstName": "Jenny",
    "lastName": "LaRusso",
    "phone": "(555) 121-2121",
    "alt_phone": "(555) 123-4567",
    "main1": false,
    "main2": true    
}, {
    "firstName": "Sensei",
    "lastName": "Miyagi",
    "phone": "(555) 444-2222",
    "alt_phone": "(555) 999-1212",
    "main1": true,
    "main2": false
}]</textarea>

我认为在正确的JSON中,键(如firstName )也需要用引号引起来。

Change your PHP code to

if(isset($_POST['data'])) {
$data = $_POST['data'];
$data = stripslashes($data); //Stripslashes removes all backslashes :)
$personArray = json_decode($data, true);
print_r($personArray);
}

Your JSON object should be this way inside the textarea

[{
"firstName": "Jenny",
"lastName": "LaRusso",
"phone": "(555) 121-2121",
"alt_phone": "(555) 123-4567",
"main1": false,
"main2": true    
}, {
"firstName": "Sensei",
"lastName": "Miyagi",
"phone": "(555) 444-2222",
"alt_phone": "(555) 999-1212",
"main1": true,
"main2": false
}]

Happy Coding :)

There does not seem to be anything wrong with your PHP code. For debugging, after setting $personArray, try adding these two lines:

var_dump($data);
var_dump($personArray);

This should lead to why you are having trouble.

Here you can see what each return type means(if $returnArray is equal to false): http://php.net/json_decode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM