我在php中有一个类返回记录数。 我用表来显示那个名字
foreach($getArtist as $getArtist)
{
echo "<tr><td>".$getArtist['name']."</td></tr>";
}
这很好,并在一行中显示每个名称
现在我想在一行中显示3个名字
foreach($getArtist as $getArtist)
{
echo "<tr>";
echo "<td>".$getArtist['name']."</td>";
echo "<td>".$getArtist['name']."</td>";
echo "<td>".$getArtist['name']."</td>";
echo "</tr>";
}
但这显示每个名称3次,但我需要在一行中显示3个名称,然后在其他行中显示其他3个名称,并且当记录完成循环完成时
答案 0 :(得分:3)
解决这个问题的几种方法。其中一种方法是分割/分块数据行。
$rowSize = 3;
$rowsOfArtists = array_chunk($getArtists, $rowSize);
if ($youNeedYourTableBalanced) {
$rows = intval(ceil(count($getArtists) / $rowSize));
$paddedLength = $rows * $rowSize;
$paddedArtists = array_pad($getArtists, $paddedLength, ' ');
$rowsOfArtists = array_chunk($paddedArtists, $rowSize);
}
foreach ($rowsOfArtists as $artists)
{
echo "<tr>";
foreach ($artists as $getArtists)
{
echo "<td>" . $getArtist['name'] . "</td>";
}
echo "</tr>";
}
答案 1 :(得分:3)
尝试:
foreach (array_chunk($getArtist, 3) as $artists) {
echo '<tr>';
foreach (array_pad($artists, 3, array('name' => ' ')) as $artist) {
echo '<td>' . $artist['name'] . '</td>';
}
echo '</tr>';
}
修改:快速将DaveRandoms修复程序插入Phils评论;)
答案 2 :(得分:0)
这是另一种方法。尝试回顾一下所概述的每种方法,因为这是一项常见的编程任务,因此请确保您了解如何解决它......
VAR $ctr = 0;
VAR $outLine = "";
foreach($getArtist as $getArtist)
{
$ctr = $ctr +1;
if ($ctr = 3)
{
echo "<tr>";
echo $outline;
echo "<td>".$getArtist['name']."</td>";
echo "</tr>";
$outline = "";
}
else
{
$outline = $outline . "<td>".$getArtist['name']."</td>";
}
}
if ($outline > "")
{
echo "<tr>";
echo $outline;
for ($i = $ctr; $i <= 3; $i++) {
echo "<td> </td>";
}
echo "</td>";
}