6

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

2 回答 2

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;
}

我使用了一个临时变量来存储和操作父类别。这会在循环结束时添加到主数组中。

于 2012-12-14T11:10:22.383 回答
-1

请使用以下代码,在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 />";
于 2012-12-14T10:59:26.597 回答