繁体   English   中英

json_encode(); 在PHP功能

[英]json_encode(); function in php

我试图使用json_encode($ loc);之后获得预期的json格式 在PHP中。

$loc['location1'] =  Array(

                       "city"    =>"test",                  
                       "addr" => Array 
                                    (
                                        "addr1"=> "test",
                                        "addr2"=> "test"

                                    ),
                     );

预期的json:

"location1": {
                "city": "test",
                "addr": {
                    "addr1": "test",
                    "addr2": "test"
                }
            }

代替:

"0": {
            "location1": {
                "city": "test",
                "addr": {
                    "addr1": "test",
                    "addr2": "test"
                }
            }
        },

请指教,谢谢。

首先,如Leggendario所说,您期望的代码不是有效的json。 要获取有效的json,它必须是一个值(如果不是数字则加引号),一个对象或一个数组。

其次,要根据您的代码获得与您的期望相似的东西,您可以这样做:

$loc = array(
    "location1" => array(
        "city" => "test",                  
        "addr" => array(
            "addr1"=> "test",
            "addr2"=> "test"
        ),
    )
);

然后致电:

json_encode($loc);

将输出:

{
    "location1": {
        "city": "test",
        "addr": {
            "addr1": "test",
            "addr2": "test"
        }
    }
}

您可以在http://jsonlint.com/中检查json输出

因此,基本上与众不同的是您将参数作为参数传递给json_encode()

stdClass和数组之间有区别。 PHP中的stdClass是通用的空类。 在javascript中,这被定义为...

var obj = {};

数组是从数字索引0开始的值的索引。在javascript中,这定义为...

var array = [];

在javascript中,您不能以精确的方式拥有关联数组,而可以在PHP中定义它们。 因此,如果在PHP中使用关联数组并使用json编码,则关联键的索引将为0。

$loc['location1'] in PHP becomes  0:[{'location'} etc...

解决方案是将其移至stdClass。 最简单的方法是将数组替换为stdClass,然后使用(object)将数组转换为对象。

<?php
$loc  = new stdClass;

$loc->location = (object) Array(
                   "city"    =>"test",                  
                   "addr" => (object) Array 
                                (
                                    "addr1"=> "test",
                                    "addr2"=> "test"
                                ),
                 );
?>

这应该可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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