Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过php在JSON中添加@sign作为对象名的一部分_Php_Json - Fatal编程技术网

如何通过php在JSON中添加@sign作为对象名的一部分

如何通过php在JSON中添加@sign作为对象名的一部分,php,json,Php,Json,我需要用php创建JSON,其中包含此内容 { "@context":"something", "type":"something" } 所以我创建了一个类 class doc { public $context; public $type; } 这给了我不带@符号的JSON { "context":"something", "type":"something" } 如果我在php中添加@,就会得到语法错误。我是否可以使用@作为变量名的一

我需要用php创建JSON,其中包含此内容

{
     "@context":"something",
     "type":"something"
}
所以我创建了一个类

class doc
{
    public $context;
    public $type;
}
这给了我不带@符号的JSON

{
    "context":"something",
    "type":"something"
}
如果我在php中添加@,就会得到语法错误。我是否可以使用@作为变量名的一部分,或者如何使用它

class doc
{
    public $@context; //this is a problem
    public $type;
}

我需要有一个应该在末尾插入MongoDB的对象

这样做可以满足您的需要

$obj = new stdClass;

$obj->{'@context'} = 'something';
$obj->type = 'somethingelse';

echo json_encode($obj);
结果

{"@context":"something","type":"somethingelse"}
或者如果您更喜欢从数组开始

$arr = [];
$arr['@context'] = 'something';
$arr['type'] = 'somethingelse';
echo json_encode($arr);
结果

{"@context":"something","type":"somethingelse"}

您可以将
关联数组
键中的
@
一起使用,并将
编码为
json

$array = array(
  '@context'  => 'something',
  'type'      => 'something'
);

print_r( json_encode( $array ) );
如果希望从类变量中获取json,可以使用以下函数:

class doc {
  public $context;
  public $type;

  public function getJson() {
    return json_encode( array(
        '@context'  => $this->context,
        'type'      => $this->type,
    ) );
  }
}


$doc = new doc;
$doc->context = 'something';
$doc->type = 'something';

print_r( $doc->getJson() );
两张照片

{
  "@context":"something",
  "type":"something"
}

你能展示一下你的json是如何产生的吗?你需要你的类还是可以简单地将数组编码成json?为什么是类?只需使用正确的键和值填充关联数组,然后对其进行编码…?如果我对预先创建的类进行注释,您提到的第一个解决方案就可以工作。如果我不评论它,它会在末尾添加@context。谢谢