我尝试使用 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"}
]}
]}