我正在处理MySQL数据库中有关城镇和城镇内区域的一些数据。
数据库如下所示
ID | NAME
1 | Manchester
2 | Manchester/North
3 | Manchester/South
4 | Manchester/East
5 | Manchester/West我尝试过一个PHP脚本,它只查找/后面的单词,并根据计数变量$j生成一个数字,但到目前为止它还不起作用。稍后,我计划将其写入变量$data所在的JSON文件中。
我的理想输出将是north south east west 4
这是脚本
$j=0;
foreach($data->objects->layer->geometries as &$h)
{
foreach($result as $row)
{
preg_match("/[^\/]+$/", $row['name'], $matches); // Town/Region
$no_slash = $matches[0]; // Region
if(strtolower($h->properties->name) == $no_slash)
{
$h->properties->id = $row['id'];
$j++;
echo $j . " " . $no_slash . "<br />";
}
}
}
echo "Number of matches: " . $j;我现在的输出是Number of matches: 0,有人知道为什么吗?
发布于 2014-10-21 22:52:29
如果我正确理解了您的问题,您可以使用以下MySQL查询:
SELECT
SUBSTRING_INDEX(NAME, '/', 1) AS city,
GROUP_CONCAT(SUBSTRING_INDEX(NAME, '/', -1) SEPARATOR ' ') AS districts,
COUNT(*) AS cnt
FROM
tablename
WHERE
NAME like '%/%'
GROUP BY
city请参阅fiddle here。
发布于 2014-10-21 22:55:38
示例数据:
CREATE TABLE t
(`ID` int, `NAME` varchar(16))
;
INSERT INTO t
(`ID`, `NAME`)
VALUES
(1, 'Manchester'),
(2, 'Manchester/North'),
(3, 'Manchester/South'),
(4, 'Manchester/East'),
(5, 'Manchester/West');查询:
SELECT
SUBSTRING(Name, 1, LOCATE('/', Name) - 1) Town,
CONCAT(GROUP_CONCAT(SUBSTRING(Name, LOCATE('/', Name) + 1)), ': ', COUNT(*)) AS Regions
FROM t
WHERE Name LIKE '%/%'
GROUP BY Town;输出:
| TOWN | REGIONS |
|------------|--------------------------|
| Manchester | North,South,East,West: 4 |https://stackoverflow.com/questions/26489420
复制相似问题