PHP Json编码一个数组

Doz*_*Doz 1 php json

我是PHP的新手(也就是JSON),但我不确定/对我所拥有的json数据的格式有信心.我正在将一个mysql转换为json以便在另一个应用程序中使用,我得到的格式如下:

    [
     {
        "category":
        {
            "catId":"1",
            "categoryName":"BABY FOOD",
            "categoryNotes":"ONLY baby food varieties which have been listed below should be used. However if your doctor or pediatrician requires a specific diet please contact your Rabbi for further advice."
        }
    },
    {
        "category":
        {
            "catId":"2",
            "categoryName":"BAKING INGREDIENTS",
            "categoryNotes":""
        }
    },
    {
        "category":
        {
            "catId":"131",
            "categoryName":"BEER",
            "categoryNotes":"See Alcoholic Drinks"
        }
    },
    {
        "category":
        {
            "catId":"4",
            "categoryName":"BEVERAGES - Powdered",
            "categoryNotes":""
        }
    },
    {
        "category":
        {
            "catId":"5",
            "categoryName":"BISCUITS",
            "categoryNotes":"Locally produced biscuits usually contain fats, oils or improvers of non-kosher origin.  There is a very large range of Israeli, South African and American kosher biscuits available locally. Even these imported biscuits and crackers (including Israeli produced goods) should only be used if marked with a reliable Rabbinic Hechsher. A 'K' on the packet alone is insufficient. Please note which products are dairy or pareve."
        }
    },
    {
        "category":
        {
            "catId":"6",
            "categoryName":"BREAD AND BAKERY GOODS",
            "categoryNotes":"Bread usually contains or comes in contact with Non-Kosher oils, fats or improvers and cannot be accepted as kosher without thorough investigation and subsequent authorisation"
        }
    },
    {
        "category":
        {
            "catId":"7",
            "categoryName":"BREAD\/CORN\/RICE CRUMBS",
            "categoryNotes":""
        }
    },
    {
        "category":
        {
            "catId":"8",
            "categoryName":"BUTTER AND DAIRY BLENDS",
            "categoryNotes":"Soft butters, butter spreads & dairy blends are NOT ACCEPTABLE unless specifically listed. Butter made from whey cream is NOT ACCEPTABLE unless produced under Rabbinic supervision"
        }
    },
    {
        "category":
        {
            "catId":"9",
            "categoryName":"BUTTERMILK and LEBEN ",
            "categoryNotes":""
        }
    },
    {
        "category":
        {
            "catId":"10",
            "categoryName":"CAKES & CAKE SHOPS",
            "categoryNotes":"Cakes and cake mixes usually contain Non-Kosher ingredients, and must only be used if they are produced under supervision <br\/> Cakes bought in a Non-Kosher cake shop, even if containing only kosher ingredients are NOT ACCEPTABLE because of the Non-Kosher utensils used in their preparation"
        }
    },
    {
        "category":
        {
            "catId":"11",
            "categoryName":"CEREALS ",
            "categoryNotes":""
        }
    },
    ...
]
Run Code Online (Sandbox Code Playgroud)

等等.

现在我不确定这是否是正确的格式,但我生成的代码如下:

            <?php


            /* soak in the passed variable or set our own */
            // $approved_prod_date = $_GET['date'];



            $link = mysql_connect('localhost','root','broncos') or die('Cannot connect to the DB');
            mysql_select_db('iKosher',$link) or die('Cannot select the DB');

            /* grab the categories from the db */
            $query=  "SELECT c.id as catId, c.name as categoryName,     c.notes as categoryNotes
                FROM        cat c
                WHERE       1=1\n";


            if(isset($_GET['catid']) && intval($_GET['catid'])) {
                $query.="AND c.id = ";
                $query.= $_GET['catid'];
            }   


            if(isset($_GET['startIndex']) && intval($_GET['startIndex'])) {
                if(isset($_GET['numItems']) && intval($_GET['numItems'])) {
                    $query .= "\nLIMIT ";
                    $query .= $_GET['startIndex'];
                    $query .= ","; 
                    $query .= $_GET['numItems'];
                }
            }




             // $query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
            $result = mysql_query($query,$link) or die('Errant query:  '.$query);
            $num=mysql_numrows($result);


            /* create one master array of the records */
              $categories = array();
              if($num) {
                while($category = mysql_fetch_assoc($result)) {
                  $categories[] = array('category'=>$category);
                }
              }
                header('Content-type: application/json');
                echo json_encode($categories);
            ?>
Run Code Online (Sandbox Code Playgroud)

根据我的代码,我这样做了吗?数组是否正确转换为JSON?

Eri*_*c G 6

json_encode()将生成有效的JSON.如有必要,您可以通过将JSON输出复制并粘贴到在线验证器(例如http://www.jsonlint.com/上的验证器)来自行验证.

如果您不确定您的数据是否正在使用正确的组织放入阵列中,那就另当别论了.但是给定一个有效的PHP数组/对象/几乎任何东西,json_encode()将生成它以JSON格式正确编码.

编辑:在你的while循环中,这段代码:

        while($category = mysql_fetch_assoc($result)) {
          $categories[] = array('category'=>$category);
        }
Run Code Online (Sandbox Code Playgroud)

构建一个如下所示的数组:("category"=> [$ catId,$ categoryName等],"category"=> [$ catId,$ categoryName等],等等)我想你会成为如果您将其更改为:更好的关闭(并且对生成的JSON更满意):

        while($category = mysql_fetch_assoc($result)) {
          $categories[] = $category;
        }
Run Code Online (Sandbox Code Playgroud)

原始代码将每个类别添加到具有相同"类别"键的$ categories数组中.但由于这个密钥对于每个类别都是重复的,因此它没有任何实际意义.