我正在 MySQL 中使用 GROUP_CONCAT 生成一个字符串。
我需要为每一行选择 2 列,即 id 和 name,我应该如何格式化查询中的字符串,以便我可以生成一个以最佳速度在 PHP 中耦合 id 和名称的数组?
例如(我的尝试): GROUP_CONCAT 制作
{"id":1,"name":"python"},{"id":2,"name":"ruby"}
然后将其转换为 PHP 中的数组。
最佳答案
类似这样的东西 -
<?php
$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'pass');
$stmt = $db->prepare("SELECT some_field, GROUP_CONCAT(CONCAT_WS('::', id, name) SEPARATOR '||') AS grp
FROM `table`
GROUP BY some_field");
$stmt->execute();
while($row = $stmt->fetchObject()) {
foreach(explode('||', $row->grp) as $pair) {
$tmp = explode('::', $pair);
$array[$row->some_field][$tmp[0]] = $tmp[1];
}
}
print_r($array);
正如 safarov 所指出的,您需要注意 group_concat_max_len 限制。
关于php - 转换为数组的最佳字符串格式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10110786/