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



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

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

所以我创建了类

class doc
{
    public $context;
    public $type;
}

这给了我没有@sign 的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"}

您可以将associative arraykeys中的@一起使用,并将encodejson一起使用。

$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"
}

最新更新