[英]Json array encode and decode the same
I encode an array to json format using the code below : 我使用以下代码将数组编码为json格式:
$arrayName[] = array('user_role_id' => 1, 'user_id' => 1);
$arrayName[] = array('user_role_id' => 2, 'user_id' => 2);
$jos = json_encode(array_values($arrayName));
The output is 输出是
[{"user_role_id":1,"user_id":1},{"user_role_id":2,"user_id":2}]
And sent it to browser. 并将其发送到浏览器。
Then after some steps browser returns the same array. 然后,在执行一些步骤之后,浏览器将返回相同的数组。
But when I try to decode 但是当我尝试解码时
$return = json_decode($jos,TRUE);
I receive the error : Array to string conversion. 我收到错误:数组到字符串的转换。
Browser didnt do anything to the array. 浏览器没有对阵列做任何事情。 Simply returns what I supply. 简单地返回我提供的。
Code flow will be like : 代码流将像:
<?php
if(isset($_GET['array']))
{
$arrayName[] = array('user_role_id' => 1, 'user_id' => 1);
$arrayName[] = array('user_role_id' => 2, 'user_id' => 2);
header('Content-Type: application/json');
echo $jos = json_encode($arrayName);
}
else
{
if(isset($_POST['jos']))
{
$jos = $_POST['jos'];
echo $new_jos = json_decode($jos,TRUE);
}
}
Can anybody please help me? 有人可以帮我吗?
What might be wrong? 可能是什么问题?
The problem is this line: 问题是这一行:
echo $new_jos = json_decode($jos,TRUE);
so you convert your json string to an array(that works!) and then echo it - that is what throws the error. 因此,您将json字符串转换为数组(有效!),然后回显它-这就是引发错误的原因。
Just use 只需使用
$new_jos = json_decode($jos,TRUE);
尝试在PHP文件中添加以下行,以便从浏览器接收数据,然后尝试解码。
header('Content-Type: application/json');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.