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.
Please use the following codes, give the index inside the while loop...
$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 />";
Related
I currently have an array that is building with the correct data by looping an object but it's giving the incorrect format:
$priceResult = array();
foreach($prices->categories as $category){
$priceResult[] = $category->category_name;
$priceResult[] = $category->category_desc;
$priceResult[] = $category->category_code;
foreach($category->products as $product){
$priceResult[] = $product->product_info->item->item_code;
foreach ($product->product_info->details as $details) {
$priceResult[] = $details->description;
$priceResult[] = $details->color;
$priceResult[] = $details->sector;
}
$priceResult[] = $product->product_info->code;
$priceResult[] = $product->product_info->item->description;
$priceResult[] = $product->product_info->item->item_type->quantity;
foreach(get_object_vars($product->prices) as $amount){
$priceResult[] = $amount;
}
}
}
This isn't associative though.
So currently, say I have one category with two products then they all print out as a single array
array({
1:category_name
2:category_desc
3:category_code
4:item_code
5:description
6:color
7:sector
8:code
9:description
10:quantity
11:amount
12:item_code
13:description
14:color
15:sector
16:code
17:description
18:quantity
19:amount
})
I'd like to get a structure where the parent level is the category_code with it's name and description, then each item_code and their own info like so:
array({
category_name
category_desc
category_code
Array(
1: item_code array(
details array(
description
color
sector
)
code
description
quantity
amount)
2: item_code array(
details array(
description
color
sector
)
code
description
quantity
amount)
)
})
How can I modify this to create the levels like I need so that it formats properly when I export to a spreadsheet
You need to split you code and init new object in the loop.
Consider the following (notice the comment in the code)
$allCategoryResult= array(); // init at first - notice naming as category and not prices
foreach($prices->categories as $category){
$categoryItem = array(); // as current category to populate
// give name to the keys and not just numbers
$categoryItem["name"] = $category->category_name;
$categoryItem["desc"] = $category->category_desc;
$categoryItem["code"] = $category->category_code;
foreach($category->products as $product){
$productItem = array(); // new product, so init new array for him
// fill all the item data with name - maybe you will need to fix the paths here
$productItem["details"] = array(); // init empty array for all the details elements
foreach ($product->product_info->details as $details) {
$detailsItem = array(); // init details array for each detail element
$detailsItem["description"] = $details->description;
$detailsItem["color"] = $details->color;
$detailsItem["sector"] = $details->sector;
$productItem["details"][] = $detailsItem; // add the detail element to the product array
}
$productItem["code"] = $product->product_info->code;
$productItem["itemDescription"] = $product->product_info->item->description;
$productItem["quantity"] = $product->product_info->item->item_type->quantity;
$productItem["amount"] = get_object_vars($product->prices);
$itemCode = $product->product_info->item->item_code;
categoryItem[$itemCode] = $productItem; // add the product to category array by his code
}
$allCategoryResult[] = $categoryItem; //add the category to all category array
}
Writing this without see you actual data is pretty hard - so I guess you will have to modify it to fit your data.
But I hop you get the idea. Good luck!
I have a sql table with some category, i get them in a array.. all fine but when i try to get data from another table foreach category, always return me for first category selected.
This is my code:
$gameguidecategoryes = array();
$gameguides = array();
$dbselectgameguidecategoryes = new DB_MSSQL;
$dbselectgameguidecategoryes->Database=$newweb_db;
$dbselectgameguidecategoryes->query("Select GameGuideCatNr,GameGuideCatName_$languageid as GameGuideCatName,GameGuideCatImage from GameGuide_Category where GameGuideCatVisible = 1 order by GameGuideCatOrder asc");
for($i=0;$i < $dbselectgameguidecategoryes->num_rows();++$i) {
if ($dbselectgameguidecategoryes->next_record()){
$GameGuideCatNr = $dbselectgameguidecategoryes->f('GameGuideCatNr');
$GameGuideCatName = $dbselectgameguidecategoryes->f('GameGuideCatName');
$GameGuideCatImage = $dbselectgameguidecategoryes->f('GameGuideCatImage');
}
$gameguidecategoryes_temp = array(
'ggcname' => $GameGuideCatName,
'ggcimg' => $GameGuideCatImage,
);
$gameguidecategoryes[$i] = $gameguidecategoryes_temp;
$dbselectgameguide = new DB_MSSQL;
$dbselectgameguide->Database=$newweb_db;
$dbselectgameguide->query("Select GameGuideID,GameGuideName_$languageid as GameGuideName from GameGuide_Content where GameGuideCat = $GameGuideCatNr and GameGuideVisible = 1 order by GameGuideOrder asc");
for($ii=0;$ii < $dbselectgameguide->num_rows();++$ii) {
if ($dbselectgameguide->next_record()){
$GameGuideID = $dbselectgameguide->f('GameGuideID');
$GameGuideName = $dbselectgameguide->f('GameGuideName');
}
$gameguides_temp = array(
'ggid' => $GameGuideID,
'ggn' => $GameGuideName,
);
$gameguides[$ii] = $gameguides_temp;
}
}
Why $gameguides return data only from first category?
Thank you
Your second loop keeps getting trashed by the first loop. e.g. Consider what happens:
You fetch your categories, and (let's pretend) there's 4 of them.
You store some information in $gameguidecategoryes[0]
You run the second query, get some content for category #0, say, 3 records
That gets stored in $gameguides[0], [1], [2]
Your outer loop ticks again, and you start on categoryes[1]
The inner loop ticks again, you get 4 records, and now you're storing them into the SAME again: $gameguides[0], [1], [2], [3], etc...
You've now trashed the data you fetched in the first loop, and will
do so for every category you fetch.
This code is very inefficient. You should learn how to use JOINs, and fetch into a single structure, e.g.
SELECT category.id, category.name, ...., content.id, content.name
FROM categories
LEFT JOIN content ON categories.id = content.category_id
ORDER BY ...
and then something like
$data = array();
while($row = fetch row from db) {
if (!isset($data[$row['category.id']]) {
$data[$row['category.id']] = array(
'name' => $row['category.name'],
'content' => array()
);
}
$data[$row['category.id']]['content'][] = array(
... save content data here
);
};
Better work on clean code
$gameguidecategoryes = $gameguides = $gameguidescategoryids = array();
$dbselectgameguidecategoryes = new DB_MSSQL;
$dbselectgameguidecategoryes->Database=$newweb_db;
$dbselectgameguidecategoryes->query("Select GameGuideCatNr,GameGuideCatName_$languageid as GameGuideCatName,GameGuideCatImage from GameGuide_Category where GameGuideCatVisible = 1 order by GameGuideCatOrder asc");
while ($dbselectgameguidecategoryes->next_record()) {
$gameguidescategoryids[] = $dbselectgameguidecategoryes->f('GameGuideCatNr');
$gameguidecategoryes[] = array(
'ggcname' => $dbselectgameguidecategoryes->f('GameGuideCatName'),
'ggcimg' => $dbselectgameguidecategoryes->f('GameGuideCatImage'),
);
}
if (count($gameguidescategoryids)) {
$dbselectgameguide = new DB_MSSQL;
$dbselectgameguide->Database=$newweb_db;
$dbselectgameguide->query("Select GameGuideID,GameGuideName_$languageid as GameGuideName from GameGuide_Content where GameGuideCat IN (".implode(',', $gameguidescategoryids).") and GameGuideVisible = 1 order by GameGuideOrder asc");
while ($dbselectgameguide->next_record()){
$gameguides[] = array(
'ggid' => $dbselectgameguide->f('GameGuideID'),
'ggn' => $dbselectgameguide->f('GameGuideName'),
);
}
}
I have created a function which is using recursion to find out childs of Given User. as shown below :
function recursionFunc($param) {
$q = "select cust_id,amount,position from testtab where parent_id = $param";
$res = mysql_query($q);
static $i = 0;
while ($row = mysql_fetch_assoc($res)) {
$i++;
recursionFunc($row['cust_id']);
}
return array('totalChild'=>$i);
}
There are two cases:
I want to call recursionFunc() for each user i am having
Recursion will be done in order to find childs of a user.
Now i want to call this function in while loop in order to fetch childs of all user i am having.
Since i am using static variable $i to store the value of childs.
Now when function will be called for the first user it returns correct value of childs but return wrong value in all other cases.
AS show Below
$cutData = "select cust_id from testtab";
$ress = mysql_query($cutData);
while ($raw = mysql_fetch_assoc($ress)) {
$response = recursionFunc($raw['cust_id']);
echo '<pre>'.$raw['cust_id'];
print_r($response);
echo '<br>';
}
Outputs
1Array ( [totalChild] => 7 ) 2Array ( [totalChild] => 10 ) 3Array ( [totalChild] => 12 )
It will be great if you can help me .
Thanks in advance.
im trying to pull out a menu in this json format :
check the output : http://www.alacarta.do/iphone/webservices/restaurants_menu2.php?r=415
The thing is that iterating of the Category plates, it duplicates the plates and then add the corresponding correct ones in each Category. all the time. check the output in the link. first category is TO SHARE. and the plates are ok, but the second category FRIES BAR, will throw again the plates from TO SHARE and then the correct plates in its category
<?
$where = empty($_GET['r'])? NULL : 'id = '. intval($_GET['r']);
$restaurant = $cmp->empresas($where,"nombre ASC")->fetch();
$json = array();
$arraynombre = array();
while($orden = $cmp->platos_tipos_orden("id_empresa = {$restaurant->id}","orden ASC")->foreachrow()):
$tipo = $cmp->platos_tipos("id = {$orden->id_tipo}")->fetch();
while($menu = $cmp->platos_menu("id_tipo = {$orden->id_tipo} AND id_empresa = {$orden->id_empresa}")->foreachrow()):
$p = $cmp->platos_lista("id = {$menu->id_plato}")->fetch();
$pnombre = $p->nombre;
$pid = $p->id;
$pprecio = $p->precio;
$arraynombre1 = array('plato_id'=>$pid,'plato_nombre'=>$pnombre,'precio'=>$pprecio);
if (in_array($arraynombre1['plato_id'], $arraynombre['plato_id'])) continue;
$arraynombre[] = $arraynombre1;
endwhile;
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
$json[] = $jsondata;
endwhile;
echo json_encode( array("menu"=>$json));
?>
Your issue is probably this line -
$arraynombre[] = $arraynombre1;
as you continually add to the array, not overwrite the previous loops values.
Try adding a key to it that is unique to each loop, ie. $orden->id_tipo -
$arraynombre[$orden->id_tipo][] = $arraynombre1;
Then you would also need to change
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
to
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre[$orden->id_tipo]);
note- it is hard to follow all your code logic, so [$orden->id_tipo] might need to be [$orden->id_empresa] or could be a similar counter var [$x] that you increase on each loop.
I'm having two tables of data "Item" and "Subsidiary" with the following structure:
ITEM
ItmCod
ItmName
SUBSIDIARY
ItmCodParent
ItmCodChild
I need to show a list of Items each with a list of its subsidiaries, like in this json:
{
"ItmCod":1,
"ItmName":"BogusItem1",
"Subsidiaries":
[
{
"ItmCodParent":1,
"ItmCodChild":15
},{
"ItmCodParent":1,
"ItmCodChild":16
}
]
},{
"ItmCod":2,
"ItmName":"BogusItem2",
"Subsidiaries":
[
{
"ItmCodParent":2,
"ItmCodChild":17
},{
"ItmCodParent":2,
"ItmCodChild":18
}
]
}
How can I add the second result set to the first one to have the nested as shown above. I have this code so far:
$sql = "SELECT ItmCod, ItmName FROM item";
$item_rows = array();
while($item_row = $database->fetch_array_assoc($item_result)){
$sub_sql = "SELECT ItmCodParent, ItmCodChild FROM subsidiary WHERE subsidiary.ItmCodParent = " . $item_row["ItmCod"];
$sub_result = $database->query($sub_sql);
$sub_rows = array();
while($sub_row = $database->fetch_array_assoc($sub_result)){
$sub_rows[] = $sub_row;
}
$item_rows[] = $item_row;
}
print json_encode($item_rows);
Thanks.
just above the line
$item_rows[] = $item_row;
simply add
$item_row['Subsidiaries']=$sub_rows;
I would do a single join query like this:
SELECT i.ItmCod AS ItmCod, i.ItmName AS ItmName, s.ItmCodChild AS ItmCodChild
FROM item AS i
INNER JOIN subsidiary AS s
ON i.ItmCod = s.ItmCodParent
Note I didn't select s.ItmCodParent as this is just redundant to i.ItmCod.
Then build the array like this:
$item_rows = array();
while($item_row = $database->fetch_array_assoc($item_result)){
$item_rows[(int)$item_row['ItmCod']]['ItmCod'] = $item_row['ItmCod'];
$item_rows[(int)$item_row['ItmCod']]['ItmName'] = $item_row['ItmCod'];
$sub_array = array(
'ItdCodParent' => $item_row['ItmCod'],
'ItmCodChild' => $item_row['ItmCodChild']
);
$item_rows[(int)$item_row['ItmCod']]['Subsidiaries'][] = $sub_array;
}
$item_rows = array_values($item_rows); // reset numerical indexes.
echo json_encode($item_rows);
I wouldn't attempt to solve this with two queries:
$sql = '
SELECT I.ItmCod, I.ItmName, S.ItmCodChild
FROM item I
LEFT JOIN subsidiary S ON (S.ItmCodParent = I.ItmCod)
';
// fetch $item_result with $sql
$item_rows = array();
while ($item_row = $database->fetch_array_assoc($item_result)) {
$cod = $item_row['ItmCod'];
if (!array_key_exists($cod, $item_rows)) {
$item_rows[$cod] = $item_row;
}
$item_rows[$cod]['Subsidiaries'] = array(
'ItmCodParent' => $cod,
'ItmCodChild' => $item_row['ItmCodChild'],
);
}
// array_values is because json_encode will keep the keys
// otherwise
print json_encode(array_values($item_rows));
That way, you aren't running an additional query for every single item row to get the subsidiaries (minimizing round-trip time, and letting the database do what it's good at).