gpt4 book ai didi

php - 如何合并现有行的值

转载 作者:行者123 更新时间:2023-11-29 20:20:20 25 4
gpt4 key购买 nike

我必须获取所有结果并推送到 HTML 表,但现有行必须合并为 1 行。

这是我的 table

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; ?>

输出如下所示:

enter image description here

我只想成为这样:

enter image description here

我只想将重复域的值组合在一行/列中

非常感谢!

最佳答案

首先从 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);

关于php - 如何合并现有行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com