2013-02-14 57 views
-1

我已經使用這個代碼,以使json對象需要進行多次JSON對象單一的文件在PHP

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中的方法需要另一個json名稱包含更多img和line的頁面秒。 它是如何做到的?

+1

*「表示在現有的JSON需要包含進一步的IMG和線另一JSON名字的網頁它該怎麼辦?」 *我很抱歉,但在英語中沒有任何意義。你可以再試一次嗎(也許請求同事幫忙?)。 – 2013-02-14 08:25:23

+1

因此,在使用回聲之前,讓你的數組像你想要的..然後回聲它與json_encode .. – Pankaj 2013-02-14 08:34:18

回答

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對象,其中每個文件將包含與領域imglines頁的數組。基本上,你只需要在PHP中創建所需的結構,就可以在JSON中獲得相同的結構。

上面的代碼應該返回是這樣的:

{"document": [{"document" : {"id":"2", 
          "name":"test", 
          "pages":[{"img":"first img","lines":" <p>first line"}, 
            {"img":"second img","lines":" <p>second line"}] 
          }} 
       ]} 
+0

我是新手。我如何創建php結構。 – rocpuneet 2013-02-14 11:33:17

+2

我的答案開始時的PHP代碼。它展示瞭如何創建一個類似於你需要的結構。如何在您的案例中創建 - 取決於您的項目。 – 2013-02-14 12:14:40