[英]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. 我试图获取存储在textarea
的json对象,并将其转换为php数组。 I assign the value of the textarea to variable like $data = $_POST['data']
. 我将textarea的值分配给$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. 当我提交文本的值时,我使用json_decode($data, true)
从JSON对象转换为php数组。 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 PHP
if(isset($_POST['submit'])) {
$data = $_POST['data'];
$personArray = json_decode($data, true);
print_r($personArray);
}
HTML 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 将您的PHP代码更改为
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 您的JSON对象应该在文本区域内是这种方式
[{
"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. 您的PHP代码似乎没有什么错。 For debugging, after setting $personArray, try adding these two lines: 为了进行调试,在设置$ personArray之后,尝试添加以下两行:
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 在这里,您可以看到每种返回类型的含义(如果$ returnArray等于false): http ://php.net/json_decode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.