douyan4470 2012-04-04 17:42
浏览 61

双重编码php多维数组发送到javascript

It is not so much as a problem as I have fixed the issue but I am stuck on the fix, I would like to know why you need to double json_encode a multidimenail array in php when you are returning it to javascript in an ajax call for example.

My Array

$jsonData = array('foo', 'bar');
$jsonData['catOne'][] = array('foo two', 'bar two');

PHP

return json_encode(json_encode($jsonData));
  • 写回答

1条回答 默认 最新

  • dsfw2154 2012-04-04 17:45
    关注

    You don't need to. The json_encode goes through the deepest elements and the json will be perfectly encoded:

    $arr = array(
        1 => array(5,6,7),
        2 => array(4,3,2),
    );
    
    var_dump(json_encode($arr));
    

    The output for that is:

    string(25) "{"1":[5,6,7],"2":[4,3,2]}"
    

    If you try:

    var_dump(json_encode(json_encode($arr)));
    

    The output will be:

    string(31) ""{\"1\":[5,6,7],\"2\":[4,3,2]}""
    

    See the difference?

    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序