我已使用此代码制作json
对象
if(mysql_num_rows($result)) {
while($document = mysql_fetch_assoc($result)) {
$documents[] = $document;
}
}
header('Content-type: application/json');
echo json_encode(array('documents'=>$documents));
它给了我像这样的文件中的单个json
{"document":[{"document":{"id":"2","name":"test","pages":"name","img":"path","lines":"data"}]}
但我需要
{"document":[{"document":{"id":"2","name":"test",pages":[{"img":"first img","lines":" <p>first line"}],pages":[{"img":"second img","lines":" <p>second line"}]}]}
现有json中的含义需要另一个包含更多img和行的json名称页面。 怎么办?
答案 0 :(得分:0)
如果您这样做:
if(mysql_num_rows($result)) {
while($document = mysql_fetch_assoc($result)) {
$document["pages"] = array();
$document["pages"][] = array("img" => "first img", "lines" => "first line");
$document["pages"][] = array("img" => "second img", "lines" => "second line");
$documents[] = $document;
}
}
json_encode(array('documents'=>$documents));
将返回JSON对象,其中每个文档将包含一个包含字段img
和lines
的网页数组。基本上,您只需要在PHP中创建所需的结构,以在JSON中获得相同的结构。
上面的代码应该返回如下内容:
{"document": [{"document" : {"id":"2",
"name":"test",
"pages":[{"img":"first img","lines":" <p>first line"},
{"img":"second img","lines":" <p>second line"}]
}}
]}