php中的{“data”:“w-file1”,“attr”:{“rel”:“file”}}的json语法是什么?

时间:2011-08-21 06:34:46

标签: php json

获取此json的php代码是什么?

{  "data": "w-file1",
   "attr": { "rel" : "file"}
}

我收到PHP Parse error: syntax error, unexpected T_DOUBLE_ARROW错误
$file = ("data" => "w-file1","attr" => ("rel" => "file"));
echo json_encode($file);

3 个答案:

答案 0 :(得分:3)

$ file和attr键一样需要是一个数组:

$file = array("data" => "w-file1","attr" => array("rel" => "file"));
echo json_encode($file);

当然,你可以内联它:

echo json_encode(array("data" => "w-file1","attr" => array("rel" => "file")));

或者,有OOP方法:

$file = new stdClass();
$file->data = 'w-file';
$file->attr = new stdClass();
$file->attr->rel = "file";
echo json_encode($file);

答案 1 :(得分:2)

您需要为$ file和attr:

指定array
$file = array("data" => "w-file1","attr" => array("rel" => "file"));
echo json_encode($file);

答案 2 :(得分:1)

$file = array(
    "data" => "w-file1",
    "attr" => array("rel" => "file")
);
echo json_encode($file);