gpt4 book ai didi

php - 如何在 PHP 中使用 foreach 循环仅回显特定的多个相同记录?

转载 作者:行者123 更新时间:2023-12-04 02:58:08 24 4
gpt4 key购买 nike

我在 PHP 中使用 foreach 循环得到这些输出。现在 foreach 中的输出如下所示。

PHP代码

<table>
<thead>
<tr>
<th>ACCOUNT NUMBER</th>
<th>CATEGORY</th>
<th>AMOUNT</th>
</tr>
</thead>
<tbody>
<?php
$sqlTxt = "SELECT * FROM table WHERE column = 'Fruits' ";
$sql = ORACLE::getInstance()->FetchArray($sqlTxt);
if(count($sql) > 0)
{
foreach($sql as $row)
{
?>
<tr>
<td><?php echo $row["ACCOUNT_NUMBER"] ;?></td>
<td><?php echo $row["CATEGORY"]; ?></td>
<td><?php echo $row["AMOUNT"]; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>

上面代码的输出是这样的

Account Number          Category            Amount
1001 Apple 30.00
1001 Mango 30.00
1001 Blueberry 30.00

1002 Durian 40.00
1002 Pineapple 40.00
1002 Jackfruit 40.00
1002 Lime 40.00

1003 Lemon 50.00
1003 Orange 50.00

我的问题是如何在类别保持循环的同时回显Account NumberAmount 一次?

我的目标是看起来像这样。在每个逗号后添加 br 标签。

Account Number          Category            Amount
1001 Apple, 30.00
Mango,
Blueberry

1002 Durian, 40.00
Pineapple,
Jackfruit,
Lime

1003 Lemon, 50.00
Orange

到目前为止,我的代码是这样的。

PHP代码

<table>
<thead>
<tr>
<th>ACCOUNT NUMBER</th>
<th>CATEGORY</th>
<th>AMOUNT</th>
</tr>
</thead>
<tbody>
<?php
$sqlTxt = "SELECT * FROM table WHERE column = 'Fruits' ";
$sql = ORACLE::getInstance()->FetchArray($sqlTxt);
if(count($sql) > 0)
{
$account_numbers = null;
$categorys = "";
$amounts = null;

foreach($sql as $row)
{
if($row['ACCOUNT_NUMBER'] !== $account_numbers)
{
if ($account_numbers !== null)
{
echo '</td></tr>';
}

echo "<tr>
<td>{$row['ACCOUNT_NUMBER']}</td>
<td>{$row['CATEGORY']}";
}
else {
echo "<br>{$selectionC['CATEGORY']}";
}
$account_numbers = $row['ACCOUNT_NUMBER'];
}
echo ' </td>
</tr>';
}
?>
</tbody>
</table>

我被困在这里了。感谢有人可以帮助我解决这个问题。

谢谢。

最佳答案

试试这个。

$account_numbers = array();
foreach($sql as $row) {
$display = FALSE;
if(!in_array($row["ACCOUNT_NUMBER"], $account_numbers)) {
$account_numbers[] = $row["ACCOUNT_NUMBER"];
$display = TRUE;
} ?>
<tr>
<td>
<?php echo $display ? $row["ACCOUNT_NUMBER"] : ""; ?>
</td>
<td><?php echo $row["CATEGORY"]; ?></td>
<td><?php echo $row["AMOUNT"]; ?></td>
</tr>
<?php }

关于php - 如何在 PHP 中使用 foreach 循环仅回显特定的多个相同记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51925670/

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