![](/img/trans.png)
[英]How can I merge two Doctrine records without null values overwriting existing values?
[英]How can I merge values of existing rows
我必须获取所有结果并推送到HTML表,但现有行必须合并为1行。
这是我的桌子
id domain php_version
-----------------------------
1 localhost 5.5.30
2 live 7.05
3 localhost 5.5.30
4 localhost 5.5.30
输出html表的代码是:
// Prepare query
$stmt = $mysqli->prepare("SELECT * FROM domains ORDER BY domain ASC LIMIT 10");
// Execute the query
$stmt->execute();
// Bind Parameters
$stmt->bind_result($id, $domain, $php_version);
<?php while ($stmt->fetch()) : ?>
<tr class="row-id-<?php echo $id; ?>">
<td class="id"><?php echo $id; ?></td>
<td class="domain"><?php echo $domain; ?></td>
<td class="php_version"><?php echo $php_version; ?></td>
</tr>
<?php endwhile; ?>
输出看起来像这样:
我只想这样:
我只想将复制的域的值合并在一行/列中
非常感谢你!
首先从mysql中获取结果,并放入常规的PHP数组(在我的代码中称为$ array),然后此代码段将执行您想要的操作:
function sort_by_php_version($a, $b)
{
if ($a["php_version"] == $b["php_version"]) {
return 0;
}
return ($a["php_version"] < $b["php_version"]) ? -1 : 1;
}
$array = [
["id"=>1, "domain"=>"localhost", "php_version"=>"5.5.30"],
["id"=>2, "domain"=>"live", "php_version"=>"7.05"],
["id"=>3, "domain"=>"localhost", "php_version"=>"5.5.30"],
["id"=>4, "domain"=>"localhost", "php_version"=>"5.5.30"],
];
usort($array, "sort_by_php_version");
$in_domain = null;
$output_array = array();
for ($i=0; $i<count($array); $i++)
{
$thisRow = $array[$i];
$domain = $thisRow["domain"];
if ($domain == $in_domain) {
$output_array[count($output_array) - 1]["php_versions"][] = $thisRow["php_version"];
} else {
$thisRow["php_versions"] = array($thisRow["php_version"]);
unset($thisRow["php_version"]);
$output_array[] = $thisRow;
$in_domain = $domain;
}
}
var_dump($output_array);
我认为我可以通过group_concat做到这一点:
SELECT domain,
GROUP_CONCAT(DISTINCT php_version SEPARATOR '\n' ) php_versions,
...
FROM domains GROUP BY domain
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.