PHP嵌套类别和子类别JSON

时间:2016-03-14 08:54:57

标签: php json

我想为我的应用程序获取带有类别和子类别的嵌套JSON,这是我的代码

// get all items from myorder table
$result = mysql_query("SELECT co.country, cl.city_code, cl.city_name
                       FROM country as co, city_list as cl
                       WHERE co.id_country = cl.id_country") or die(mysql_error());

$response["location"] = array();

while ($row = mysql_fetch_assoc($result)) {
    $categories['Cities'][] = array(
            'code'         => $row['city_code'],
            'city'         => $row['city_name'],
    );
}

foreach ($categories as $key => $value) {
    $category_data[] = array(
        'category'      => $key,
        'category_list' => $value,
    );
}

array_push($response["location"], $categories);
// echoing JSON response
echo json_encode($response);

这就是结果:

 {
location: [
    {
        USA: {
            Country: "USA"
            Cities: [
                {
                    code: "AL",
                    city: "ALABAMA"
                },
                {
                    code: "AR",
                    city: "Arkansas"
                },
                {
                    code: "DC",
                    city: "Distric of Columbia"
                },
                {
                    code: "LA",
                    city: "Louisiana"
                }
                ]
            }
        }

    ]
}

我想要这种格式:

{
location: [
    Country: "USA"
    Cities: [
        {
            code: "AL",
            city: "ALABAMA"
        },
        {
            code: "AR",
            city: "Arkansas"
        },
        {
            code: "DC",
            city: "Distric of Columbia"
        },
        {
            code: "LA",
            city: "Louisiana"
        },


    ]
}

我怎样才能做到这一点?有什么参考我可以研究一下吗? 有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

首先,在您的请求中按国家/地区名称排序。

while ($row = mysql_fetch_assoc($result)) {
    if (! isset($categories[$row['country']])) {
          $categories[$row['country']] = array('Country' => $row['country']);
          $categories[$row['country']]['Cities'] = array();
    }

    $categories[$row['country']]['Cities'][] = array(
        'code'         => $row['city_code'],
        'city'         => $row['city_name'],
    );

}

... rest of your code

顺便说一下,你应该停止使用mysql_ *函数并使用mysqli_ *。正如在每篇文章中所写的那样......