私のターゲットJSONオブジェクトは、この構造のようになります
[
{
"categories":[
{
"CATEGORY_ID":"Drinks",
"subcategorys":[
{
"subcateory_ID":"beer",
"items":[
{
"item_NAME":"yuengling",
"item_id":1
},
{
"item_NAME":"miller lite",
"item_id":2
}
],
"subcateory_ID":"wine",
"items":[
{
"item_NAME":"white zin",
"item_id":3
}
]
}
]
},
{
"CATEGORY_ID":"food",
"subcategorys":[
{
"subcateory_ID":"sandwiches",
"items":[
{
"item_NAME":"hamburger",
"item_id":1
},
{
"item_NAME":"ham & cheese",
"item_id":2
}
],
"subcateory_ID":"sides",
"items":[
{
"item_NAME":"fries",
"item_id":3
}
]
}
]
}
]
}
]
私のSQLクエリはこのようなものです
SELECT categories.id, category_name FROM categories WHERE site_id = 1
SELECT sub_categories.id, sub_category_name FROM sub_categories WHERE site_id = 1 AND category_id = 1
SELECT items.id, item_name FROM items WHERE site_id = 1 AND sub_category_id = 1 AND site_id = 1
各選択後にネストされたループを使用して、php でこの json を作成する最も効率的な方法を見つけるのに苦労しました。
これは私が降り始めた道です
$query1 = "SELECT categories.id, category_name FROM categories WHERE site_id = ".$siteId;
$result1 = mysqli_query ($dbc, $query1) or trigger_error("Query: $query1\n<br />MySQL Error: " . mysqli_error($dbc));
if($result1 === FALSE)
{
echo(mysqli_error()); // TODO: better error handling
} else
{
$categoriesJson = ' [ {"categories":[{'
while( $row = mysqli_fetch_array($result1) )
{
$category = $row['category_name'];
$categoriesJson = $categoriesJson.'"CATEGORY_ID":"'.$category.'","subcategorys":[{';
// Make the query:
$query2 = "SELECT sub_categories.id, sub_category_name FROM sub_categories WHERE site_id = ".$siteId . " AND category_id = ". $row['id'];
$result2 = mysqli_query ($dbc, $query2) or trigger_error("Query: $query2\n<br />MySQL Error: " . mysqli_error($dbc));
if($result2 === FALSE)
{
echo(mysqli_error());
}
else
{
while( $row2 = mysqli_fetch_array($result2) )
{
$subcategory = $row2['sub_category_name'];
$categoriesJson = $categoriesJson.'"subcateory_ID":"'.$subcategory.'","items":[{';
$query3 = "SELECT items.id, item_name FROM items WHERE site_id = ".$siteId . " AND sub_category_id = ". $row2['id'] . " AND site_id = ".$siteId;
$result3 = mysqli_query ($dbc, $query3) or trigger_error("Query: $query3\n<br />MySQL Error: " . mysqli_error($dbc));
if($result3 === FALSE)
{
echo(mysqli_error());
} else
{
while( $row3 = mysqli_fetch_array($result3) )
{
$itemname = $row3['item_name'];
$itemid = $row3['id'];
$categoriesJson = $categoriesJson.'"itemName":"'.$itemname.'","itemId":"'.$itemid.'"';
}
$categoriesJson = $categoriesJson.'}]';
}
}
$categoriesJson = $categoriesJson.'}]';
}
$categoriesJson = $categoriesJson.'}]';
}