将json添加到数组而不丢失格式

时间:2016-09-25 10:25:25

标签: php arrays json

我尝试将下面的简单json添加到我的API中的数组

$result = array();
...
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$json =  json_encode($arr);               
$result['json'] = $json;

return $result;

但是在将它添加到我的数组后,它会像这样松散格式。

请查看红色箭头指向并与屏幕截图2进行比较。

enter image description here
我想要的是我的json应该显示为

enter image description here

我该如何防止它。任何帮助或建议将非常感谢

2 个答案:

答案 0 :(得分:2)

这里似乎发生的是双重编码,你的$ result数组也被编码,然后它再次编码$ result ['json'],导致你看到的输出。

$result = array();
...
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$json =  json_encode($arr);               
$result['json'] = $json;

return $result; // either you are using a framework, or not showing a step, but this also seems to be encoded before being sent back to the client.

鉴于我可以推断出你向我们展示的内容,在将数组分配给$ result ['json']之前不要编码你的数组

$result = array();
...          
$result['json'] = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

return $result;

然后应该给你你想要的东西。

答案 1 :(得分:0)

$result = array();
$result['json']= array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$json =  json_encode($result);               

return $json;

这个解决方案对我有用。