Iam trying with the json_encoding for about two hours but iam not getting the output as required. Actually this is a requirement for the mobile application developer who is asking in the format which i will explain here.The code below is what i have tried:
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 />";
The Output is :
"JsonOutput":[{"ParentCategory":"Animals"},{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"},
{"ParentCategory":"Art"},{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"},{"ChildCategory":"Abstract"}]}
Here , in the above output the parent category array is empty without its child category array. I want to store all the child category array in its parent category array and finally i have to store both parent and child category into the JsonOutput array so i want the output as
"JsonOutput":[{
"ParentCategory":"Animals" : [{
{"ChildCategory":"Bear"},{"ChildCategory":"Deer"},{"ChildCategory":"Dolphins"}
]}
"ParentCategory":"Arts" : [{
{"ChildCategory":"Hand Painting"},{"ChildCategory":"Painting"},{"ChildCategory":"3D"}, {"ChildCategory":"Abstract"}
]}
]}
You probably need to do this (only the important bits are shown):
$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;
}
I used a temporary variable for storing and manipulating the parent category. This gets added to the main array at the end of loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With