php中{"data":"w-file1","attr";


What's json syntax for {"data":"w-file1","attr":{"rel":"file"}} in php?

得到这个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);

$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")));

或者,有一种面向对象的方法:

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

您需要为$file指定array和attr:

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