1

私のターゲット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.'}]';
}
4

1 に答える 1

0

この特定のコードはテストされていませんが、一般的なアイデアは十分にテストされており、理解するのが難しくないことを願っています. アイデアは、配列を正しい方法で構築してから、json_encode を使用することです。そのカテゴリ/サブカテゴリが既に存在する場合はすべての行をチェックすることで、適切な形式を取得していることを確認します。json では識別子 ( などDrinks: {...}) を使用しないため、一時配列を使用して、それらがいっぱいになったら追加する必要があります。

より一般的なコードを探したり、google で php ピボット関数を検索したりすることもできます。

<?php
$sql = "SELECT categories.category_name AS CATEGORY_ID, sub_categories.sub_category_name AS subcategory_ID, items.id, items.item_name 
        FROM categories
        LEFT JOIN sub_categories ON (categories.id = sub_categories.category_id and sub_categories.site_id = 1)
        LEFT JOIN items ON (sub_categories.id = items.sub_category_id and items.site_id = 1)
        WHERE categories.site_id = 1";
// ...

$tempCategoryArray = array();
$tempSubCategoryArray = array();
$categoriesArray = array("categories" => array());
$category = $sub_category = "";
while($row = mysqli_fetch_array($result1)) {
    // If we have a new category, let's start anew
    if($row['CATEGORY_ID'] != $category) {
        // Add the temporary array to the main one
        if(!empty($tempCategoryArray)) {
            $categoriesArray['categories'][] = $tempCategoryArray;
        }
        $tempCategoryArray = array();
        $tempCategoryArray['CATEGORY_ID'] = $row['CATEGORY_ID'];
        $tempCategoryArray['subcategorys'] = array();
    }
    // Same here, if a new sub, let's start fresh
    if($row['subcategory_ID'] != $sub_category) {
        // Add it to the tempCategory
        if(!empty($tempSubCategoryArray)) {
            $tempCategoryArray['subcategorys'] = $tempSubCategoryArray;
        }
        $tempSubCategoryArray = array();
        $tempSubCategoryArray['subcategory_ID'] = $row['subcategory_ID'];
        $tempSubCategoryArray['items'] = array();
    }

    // Finally, no need for temporary arrays with items, since they have no sub-array
    $tempSubCategoryArray['items'][] = array('item_NAME': $row['item_name'], 'item_id': $row['id']);
}

$categoryJson = json_encode($categoryArray);
于 2013-02-01T16:46:07.333 に答える