2012-12-14 31 views
5

Iam嘗試使用json_encoding大約兩個小時,但iam沒有根據需要獲取輸出。其實,這是移動應用程序開發人員是誰在問我將在下面解釋更換預定代碼格式的要求是什麼,我曾嘗試:帶有父類別和子類別的PHP json_encoding數據

include_once("class_connection.php"); 

//Getting the Parent Category 

$sqlStr = mysql_query("select catname , id from `category` where `parentid`='0'"); 
$jsonArray = array(); 

while ($fetchStr = mysql_fetch_assoc($sqlStr)) { 

    $jsonArray[] = array("ParentCategory" => $fetchStr["catname"]); 
     $id = $fetchStr['id']; 

    //Getting child categories from the above parent 

    $sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'"); 

    while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) { 

     $jsonArray[] = array("ChildCategory" => $fetchchildStr["catname"]); 
    } 

} 

echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />"; 

輸出爲:

"JsonOutput":[{"ParentCategory":"Animals"},{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"}, 
{"ParentCategory":"Art"},{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"},{"ChildCategory":"Abstract"}]} 

這裏,在上面的輸出中,父類別數組是空的,沒有它的子類別數組。我想存儲所有的子類別排列在它的父類陣列,最後我不得不既父和子類別存儲到JsonOutput陣列,所以我想輸出作爲

"JsonOutput":[{ 
"ParentCategory":"Animals" : [{ 
    {"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"} 
]} 
"ParentCategory":"Arts" : [{ 
    {"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"}, {"ChildCategory":"Abstract"} 
]} 
]} 
+3

您所需的輸出對我來說看起來不像是有效的JSON。 –

+4

您似乎在尋找格式化(或美化)您的JSON輸出。但爲什麼這是必要的呢?人類是否會處理它? –

+0

@Pekka:仔細一看,這不一定關於美化:''ParentCategory「:」Animals「:[{'< - 只是創建無效的JSON。 – hakre

回答

2

你可能需要做到這一點(只有重要的位顯示):

$jsonArray = array(); 
while ($parentCat = mysql_fetch_assoc($sqlStr)) { 
    $temp = array(
     "ParentCategory" => $parentCat["catname"] 
    ); 
    while ($childCat = mysql_fetch_assoc($sqlChildStr)) { 
     $temp["ChildCategory"][] = array(
      "ChildCategory" => $childCat["catname"] 
     ); 
    } 
    $jsonArray[] = $temp; 
} 

我使用的臨時變量存儲並操縱父類別。這被添加到循環結尾的主數組中。

+0

非常感謝幫助。它工作正常。 – raduns

0

請使用下面的代碼,給指數while循環中......

$jsonArray = {}; 
while ($fetchStr = mysql_fetch_assoc($sqlStr)) { 

    //$jsonArray[] = array("ParentCategory" => $fetchStr["catname"]); 
     $id = $fetchStr['id']; 

    //Getting child categories from the above parent 

    $sqlChildStr = mysql_query("SELECT catname,id,parentid FROM `category` where `parentid`='$id'"); 

    while ($fetchchildStr = mysql_fetch_assoc($sqlChildStr)) { 

     $jsonArray["ParentCategory"][$fetchStr["catname"]] = array("ChildCategory" => $fetchchildStr["catname"]); 
    } 

} 

echo json_encode(array("JsonOutput" => $jsonArray)) . "<br />";