php返回省市区三级联动数据
时间: 2024-02-05 22:35:37 浏览: 85
可以通过查询数据库或者调用第三方API来获取省市区三级联动数据,以下是一个简单的示例:
1. 创建数据库表
首先,在数据库中创建一个表用于存储省市区数据,可以按照以下结构来设计:
```
CREATE TABLE `regions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`parent_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
2. 插入数据
然后,向表中插入省市区数据,例如:
```
INSERT INTO regions (name, parent_id) VALUES
('北京市', 0),
('天津市', 0),
('河北省', 0),
('山西省', 0),
('内蒙古自治区', 0),
('辽宁省', 0),
('吉林省', 0),
('黑龙江省', 0),
('上海市', 0),
('江苏省', 0),
('浙江省', 0),
('安徽省', 0),
('福建省', 0),
('江西省', 0),
('山东省', 0),
('河南省', 0),
('湖北省', 0),
('湖南省', 0),
('广东省', 0),
('广西壮族自治区', 0),
('海南省', 0),
('重庆市', 0),
('四川省', 0),
('贵州省', 0),
('云南省', 0),
('西藏自治区', 0),
('陕西省', 0),
('甘肃省', 0),
('青海省', 0),
('宁夏回族自治区', 0),
('新疆维吾尔自治区', 0),
('台湾省', 0),
('香港特别行政区', 0),
('澳门特别行政区', 0),
('北京市', 1),
('东城区', 2),
('西城区', 2),
('崇文区', 2),
('宣武区', 2),
('朝阳区', 2),
('丰台区', 2),
('石景山区', 2),
('海淀区', 2),
('门头沟区', 2),
('房山区', 2),
('通州区', 2),
('顺义区', 2),
('昌平区', 2),
('大兴区', 2),
('怀柔区', 2),
('平谷区', 2),
('密云县', 2),
('延庆县', 2),
('和平区', 3),
('河东区', 3),
('河西区', 3),
('南开区', 3),
('河北区', 3),
('红桥区', 3),
('塘沽区', 3),
('汉沽区', 3),
('大港区', 3),
('东丽区', 3),
('西青区', 3),
('津南区', 3),
('北辰区', 3),
('武清区', 3),
('宝坻区', 3),
('宁河县', 3),
('静海县', 3),
('蓟县', 3),
('石家庄市', 4),
('长安区', 5),
('桥西区', 5),
('新华区', 5),
('井陉矿区', 5),
('裕华区', 5),
('藁城区', 5),
('鹿泉区', 5),
('栾城区', 5),
('井陉县', 5),
('正定县', 5),
('行唐县', 5),
('灵寿县', 5),
('高邑县', 5),
('深泽县', 5),
('赞皇县', 5),
('无极县', 5),
('平山县', 5),
('元氏县', 5),
('赵县', 5),
('辛集市', 5),
('晋州市', 5),
('新乐市', 5),
('唐山市', 6),
('路南区', 7),
('路北区', 7),
('古冶区', 7),
('开平区', 7),
('丰南区', 7),
('丰润区', 7),
('曹妃甸区', 7),
('滦县', 7),
('滦南县', 7),
('乐亭县', 7),
('迁西县', 7),
('玉田县', 7),
('遵化市', 7),
('迁安市', 7),
('秦皇岛市', 8),
('海港区', 9),
('山海关区', 9),
('北戴河区', 9),
('青龙满族自治县', 9),
('昌黎县', 9),
('抚宁县', 9),
('卢龙县', 9);
```
3. 查询数据
最后,通过查询数据库获取省市区数据,例如:
```
<?php
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '123456';
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
$provinces = $db->query('SELECT id, name FROM regions WHERE parent_id = 0')->fetchAll(PDO::FETCH_ASSOC);
foreach ($provinces as &$province) {
$citys = $db->query(sprintf('SELECT id, name FROM regions WHERE parent_id = %d', $province['id']))->fetchAll(PDO::FETCH_ASSOC);
foreach ($citys as &$city) {
$districts = $db->query(sprintf('SELECT id, name FROM regions WHERE parent_id = %d', $city['id']))->fetchAll(PDO::FETCH_ASSOC);
$city['children'] = $districts;
}
$province['children'] = $citys;
}
echo json_encode($provinces);
?>
```
这样,就可以得到一个包含省市区三级联动数据的JSON字符串。
阅读全文