PHP 嵌套类别和子类别 JSON


PHP nested category and subcategory 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"
        },

    ]
}

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

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

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_*。正如SO上的每篇帖子中所写的那样..