使用PHP从上到下打印数组,而不是从左到右

时间:2022-08-22 11:37:31

I am trying to write a logic to display records top to bottom instead of left to right in the table.

我正在尝试编写一个逻辑来显示从上到下而不是从左到右的表中的记录。

Here is my attempt:

这是我的尝试:

<?php $options = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); ?>
<table border="1" colspan="0" cellspan="0">
    <?php
    $htmldata = "";
    $counter = 1;

    $rowcount = ceil(count($options) / 3);

    for ($i = 0; $i < count($options); $i++) {
        echo $counter % 3 ."<br/>";

        if ($counter % 3 == 1) {
            $htmldata .= "<tr>";
            $htmldata .= "<td>".$options[$i]."</td>";
        }
        if ($counter % 3 == 2) {
            $htmldata .= "<td>".$options[$i]."</td>";
        }
        if ($counter % 3 == 0) {
            $htmldata .= "<td>".$options[$i]."</td>";
            $htmldata .= "</tr>";
        }
        $counter++;
    }
    echo $htmldata;
    exit;
    ?>
</table>

Below is current code output in the table.

下面是表中的当前代码输出。

使用PHP从上到下打印数组,而不是从左到右

But I need the table to output like this.

但是我需要这个表格来输出。

使用PHP从上到下打印数组,而不是从左到右

How can I achieve this?
Can you guys please help me to write this logic?
Also, it currently is showing 10 records, but it may be much more or less, so we need the code to be dynamic.

我如何做到这一点?你们能帮我写一下这个逻辑吗?此外,它目前显示了10条记录,但可能或多或少,所以我们需要代码是动态的。

Any help will be appreciated. Thanks in advance!

如有任何帮助,我们将不胜感激。提前谢谢!

NOTE: It must have only 3 columns for any numbers of records and output must be same as displayed in the second picture example for 10 records.

注意:对于任意数量的记录,它必须只有3列,输出必须与第二个图片示例中显示的10条记录相同。

4 个解决方案

#1


4  

Hopefully my final answer (after all the editing)

<?php
// feel free to change the values in these variables
$options = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
$numCols = 3; // the number of columns to present
$pad = false; // whether to add blank <td> in final row

// don't alter these variables
$rows = (int)ceil(count($options) / $numCols); // number of rows of the column with most rows
$c = count($options) % $numCols; // how many columns have records on the final row
$col = 1; // current column

// iterate over the columns
for ($j = 0; $j < $numCols; $j++) {
    // iterate over rows
    for ($i = 0; $i < $rows; $i++) {
        // if iteration is last line and on a column with extra data
        // or if the iteration is not the last row
        // or if the last row perfectly fits the column count
        if (($col <= $c && $i == $rows - 1) || $i != $rows - 1 || $c == 0) {
            // remove the first element from the options array
            $arr[$i][$j] = array_shift($options);
        }
    }
    // move onto the next column
    $col++;
}

// create the extra <td> elements in the final row
if ($pad) {
    $arr[count($arr) - 1] = array_pad($arr[count($arr) - 1], $numCols, null);
}
?>
<table border="1" colspan="0" cellspan="0">
    <?php for ($i = 0; $i < count($arr); $i++) { ?>
    <tr>
        <?php for ($j = 0; $j < count($arr[$i]); $j++) { ?>
        <td><?= $arr[$i][$j]; ?></td>
        <?php } ?>
    </tr>
    <?php } ?>
</table>

I have edited the answer I originally posted as it was broken and long-winded. This solution is neater and works better than the previous.

我编辑了我最初发布的答案,因为它是破碎的和冗长的。这个解决方案比以前更整洁,工作得更好。

At the time of writing this answer I hadn't seen the edit about a fixed number of columns so there is a variable that can change the column count if necessary. Feel free to change the column count ($numCols) and also the number of elements in the array. This is here should you ever need to change the requirements of your application.

在编写这个答案的时候,我还没有看到关于固定列数的编辑,所以如果需要的话,有一个变量可以更改列计数。可以随意更改列计数($numCols)和数组中的元素数量。如果您需要更改应用程序的需求,这里提供了这个功能。

There are a few thing you can fiddle with if you like. They are as follows:

如果你喜欢的话,有一些东西你可以去摆弄。他们如下:

  • $options
    This is simply your array of data. This can be whatever the heck you want. The table will be created according to this data from top to bottom as requested.
  • $options:这只是您的数据数组。这可以是你想要的任何东西。根据要求,将根据该数据从上到下创建表。
  • $numCols
    Perhaps you want to rename this, it really doesn't matter. It is short for 'number of columns' and is exactly that; whatever integer you put here, you will get that many <td> elements in that row, or, if you prefer to not read them in the HTML way, then you will have that many columns with the subsequent row count depending on the provided data.
  • $numCols也许你想重命名它,它真的不重要。它是“列数”的缩写,正是如此;无论您在这里输入的是什么整数,您都将在该行中获得许多元素,或者,如果您不喜欢以HTML的方式读取它们,那么您将拥有许多列,并根据提供的数据进行后续行计数。
  • $pad
    This is because I noticed that the last row had fewer records - unless $options length was divisible, with no remainder, by $numCols.
    To fix this I added this choice. It is used after the for loop has created the array, and will just pad out the final row with null values so that you don't have the blank space to the right of the final row.
    Naturally, it is entirely up to you whether you want that. Personally, I'd opt to set $pad to true since I think that it makes the table look neater.
  • 这是因为我注意到最后一行的记录更少——除非$options长度可以被$numCols除除,没有余数。为了解决这个问题,我添加了这个选项。它是在for循环创建了数组之后使用的,它将会用null值填充最后一行,这样就不会在最后一行的右边有空白了。当然,这完全取决于你是否想要。就我个人而言,我选择将$pad设置为true,因为我认为它使表格看起来更整洁。

The rest of the code I encourage you to not alter as it will work correctly.
Obviously, if you use this code a lot then you can wrap it in a function; although if you do this, I strongly discourage that you do as you originally did and start creating a string to store your table in.
It is bad practice and can cause mistakes. For instance, you might forget to close the table - something you did by using the exit keyword - which would go unnoticed by many modern browsers as they would still show the desired outcome, but your code would then fail a validator. Therefore, if you wish to use a function ensure that it is only the PHP code. Then just call it on an array and iterate as I have done at the end (by which I mean, the table part with the for loop is not part of the function).

我鼓励您不要更改其余的代码,因为它将正常工作。显然,如果你经常使用这段代码,你可以把它封装在一个函数中;尽管如果您这样做,我强烈建议您不要像原来那样做,并开始创建一个字符串来存储您的表。这是不好的做法,可能会导致错误。例如,您可能会忘记关闭表——您使用exit关键字所做的事情——这在许多现代浏览器中是不会被注意到的,因为它们仍然显示所需的结果,但是您的代码随后会失败验证器。因此,如果希望使用函数,请确保它只是PHP代码。然后在数组上调用它,并像我在最后所做的那样进行迭代(我的意思是,带有for循环的表部分不是函数的一部分)。

I honestly can't believe how long I spent doing this!

我真的不敢相信我花了这么长时间做这件事!

使用PHP从上到下打印数组,而不是从左到右

#2


1  

Try this:

试试这个:

<?php
function getTableHtml(array $data, int $colLength): string
{
    $result = '';

    $rowNumber = 0;
    $rows = [];
    foreach (array_values($data) as $k => $v) {
        if ($k % $colLength === 0) {
           ++$rowNumber;
           $rows[$rowNumber] = '';
        }

        $rows[$rowNumber] .= '<td>';
        $rows[$rowNumber] .= htmlentities($v);
        $rows[$rowNumber] .= '</td>';
        $rows[$rowNumber] .= PHP_EOL; // optional formatting
    }

    $result = '<table><tr>' . join('</tr><tr>', $rows) . '</tr></table>';

    return $result;
}

Try live: https://3v4l.org/A7erq

试着生活:https://3v4l.org/A7erq

#3


1  

Try this:

试试这个:

<?php
$options = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16");
$elems = count($options);
// set the # of rows you want to show
$rows=5;
// calculate # of columns
$cols=ceil($elems/$rows);


echo "<table style='border: 2px solid black;'>";
for($r=0; $r<$rows; $r++)
{
    echo '<tr>';
    $shift=0;
    for($c=0; $c<$cols; $c++)
    {
        echo "<td style='border: 1px solid blue;'>";
        if($r+$shift < $elems)
        {
        echo $options[$r+$shift];
        }
        echo '</td>';

        $shift+=$rows;
    }
    echo '</tr>';
}
echo '</table>';
?>

#4


1  

You can do something links this. first loop and store element in proper way. then simply it in table. NOTE :

你可以做一些链接。第一个循环并以正确的方式存储元素。然后放在表中。注意:

You have to fix row or column (Here I am assuming you have fix 3 rows). Your desired output has issue as first row has 4 rows and others have 3

您必须修复行或列(这里假设您有修复3行)。您想要的输出有问题,因为第一行有4行,其他行有3行

<?php 
$options = range(1,10);
$new_array = array();
$rows = 3;
foreach ($options as $value) {
  $new_array[$value % $rows][] = $value;    
}

?>
<table border="1" colspan="0" cellspan="0">
    <?php
        $htmldata = "";
        foreach ($new_array as $key => $value) {
          echo "<tr>";
          foreach ($value as $option) {
            echo "<td>".$option."</td>";
          }
          echo "</tr>";
        }  
    ?>
</table>

Output will be

输出将

使用PHP从上到下打印数组,而不是从左到右

#1


4  

Hopefully my final answer (after all the editing)

<?php
// feel free to change the values in these variables
$options = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
$numCols = 3; // the number of columns to present
$pad = false; // whether to add blank <td> in final row

// don't alter these variables
$rows = (int)ceil(count($options) / $numCols); // number of rows of the column with most rows
$c = count($options) % $numCols; // how many columns have records on the final row
$col = 1; // current column

// iterate over the columns
for ($j = 0; $j < $numCols; $j++) {
    // iterate over rows
    for ($i = 0; $i < $rows; $i++) {
        // if iteration is last line and on a column with extra data
        // or if the iteration is not the last row
        // or if the last row perfectly fits the column count
        if (($col <= $c && $i == $rows - 1) || $i != $rows - 1 || $c == 0) {
            // remove the first element from the options array
            $arr[$i][$j] = array_shift($options);
        }
    }
    // move onto the next column
    $col++;
}

// create the extra <td> elements in the final row
if ($pad) {
    $arr[count($arr) - 1] = array_pad($arr[count($arr) - 1], $numCols, null);
}
?>
<table border="1" colspan="0" cellspan="0">
    <?php for ($i = 0; $i < count($arr); $i++) { ?>
    <tr>
        <?php for ($j = 0; $j < count($arr[$i]); $j++) { ?>
        <td><?= $arr[$i][$j]; ?></td>
        <?php } ?>
    </tr>
    <?php } ?>
</table>

I have edited the answer I originally posted as it was broken and long-winded. This solution is neater and works better than the previous.

我编辑了我最初发布的答案,因为它是破碎的和冗长的。这个解决方案比以前更整洁,工作得更好。

At the time of writing this answer I hadn't seen the edit about a fixed number of columns so there is a variable that can change the column count if necessary. Feel free to change the column count ($numCols) and also the number of elements in the array. This is here should you ever need to change the requirements of your application.

在编写这个答案的时候,我还没有看到关于固定列数的编辑,所以如果需要的话,有一个变量可以更改列计数。可以随意更改列计数($numCols)和数组中的元素数量。如果您需要更改应用程序的需求,这里提供了这个功能。

There are a few thing you can fiddle with if you like. They are as follows:

如果你喜欢的话,有一些东西你可以去摆弄。他们如下:

  • $options
    This is simply your array of data. This can be whatever the heck you want. The table will be created according to this data from top to bottom as requested.
  • $options:这只是您的数据数组。这可以是你想要的任何东西。根据要求,将根据该数据从上到下创建表。
  • $numCols
    Perhaps you want to rename this, it really doesn't matter. It is short for 'number of columns' and is exactly that; whatever integer you put here, you will get that many <td> elements in that row, or, if you prefer to not read them in the HTML way, then you will have that many columns with the subsequent row count depending on the provided data.
  • $numCols也许你想重命名它,它真的不重要。它是“列数”的缩写,正是如此;无论您在这里输入的是什么整数,您都将在该行中获得许多元素,或者,如果您不喜欢以HTML的方式读取它们,那么您将拥有许多列,并根据提供的数据进行后续行计数。
  • $pad
    This is because I noticed that the last row had fewer records - unless $options length was divisible, with no remainder, by $numCols.
    To fix this I added this choice. It is used after the for loop has created the array, and will just pad out the final row with null values so that you don't have the blank space to the right of the final row.
    Naturally, it is entirely up to you whether you want that. Personally, I'd opt to set $pad to true since I think that it makes the table look neater.
  • 这是因为我注意到最后一行的记录更少——除非$options长度可以被$numCols除除,没有余数。为了解决这个问题,我添加了这个选项。它是在for循环创建了数组之后使用的,它将会用null值填充最后一行,这样就不会在最后一行的右边有空白了。当然,这完全取决于你是否想要。就我个人而言,我选择将$pad设置为true,因为我认为它使表格看起来更整洁。

The rest of the code I encourage you to not alter as it will work correctly.
Obviously, if you use this code a lot then you can wrap it in a function; although if you do this, I strongly discourage that you do as you originally did and start creating a string to store your table in.
It is bad practice and can cause mistakes. For instance, you might forget to close the table - something you did by using the exit keyword - which would go unnoticed by many modern browsers as they would still show the desired outcome, but your code would then fail a validator. Therefore, if you wish to use a function ensure that it is only the PHP code. Then just call it on an array and iterate as I have done at the end (by which I mean, the table part with the for loop is not part of the function).

我鼓励您不要更改其余的代码,因为它将正常工作。显然,如果你经常使用这段代码,你可以把它封装在一个函数中;尽管如果您这样做,我强烈建议您不要像原来那样做,并开始创建一个字符串来存储您的表。这是不好的做法,可能会导致错误。例如,您可能会忘记关闭表——您使用exit关键字所做的事情——这在许多现代浏览器中是不会被注意到的,因为它们仍然显示所需的结果,但是您的代码随后会失败验证器。因此,如果希望使用函数,请确保它只是PHP代码。然后在数组上调用它,并像我在最后所做的那样进行迭代(我的意思是,带有for循环的表部分不是函数的一部分)。

I honestly can't believe how long I spent doing this!

我真的不敢相信我花了这么长时间做这件事!

使用PHP从上到下打印数组,而不是从左到右

#2


1  

Try this:

试试这个:

<?php
function getTableHtml(array $data, int $colLength): string
{
    $result = '';

    $rowNumber = 0;
    $rows = [];
    foreach (array_values($data) as $k => $v) {
        if ($k % $colLength === 0) {
           ++$rowNumber;
           $rows[$rowNumber] = '';
        }

        $rows[$rowNumber] .= '<td>';
        $rows[$rowNumber] .= htmlentities($v);
        $rows[$rowNumber] .= '</td>';
        $rows[$rowNumber] .= PHP_EOL; // optional formatting
    }

    $result = '<table><tr>' . join('</tr><tr>', $rows) . '</tr></table>';

    return $result;
}

Try live: https://3v4l.org/A7erq

试着生活:https://3v4l.org/A7erq

#3


1  

Try this:

试试这个:

<?php
$options = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16");
$elems = count($options);
// set the # of rows you want to show
$rows=5;
// calculate # of columns
$cols=ceil($elems/$rows);


echo "<table style='border: 2px solid black;'>";
for($r=0; $r<$rows; $r++)
{
    echo '<tr>';
    $shift=0;
    for($c=0; $c<$cols; $c++)
    {
        echo "<td style='border: 1px solid blue;'>";
        if($r+$shift < $elems)
        {
        echo $options[$r+$shift];
        }
        echo '</td>';

        $shift+=$rows;
    }
    echo '</tr>';
}
echo '</table>';
?>

#4


1  

You can do something links this. first loop and store element in proper way. then simply it in table. NOTE :

你可以做一些链接。第一个循环并以正确的方式存储元素。然后放在表中。注意:

You have to fix row or column (Here I am assuming you have fix 3 rows). Your desired output has issue as first row has 4 rows and others have 3

您必须修复行或列(这里假设您有修复3行)。您想要的输出有问题,因为第一行有4行,其他行有3行

<?php 
$options = range(1,10);
$new_array = array();
$rows = 3;
foreach ($options as $value) {
  $new_array[$value % $rows][] = $value;    
}

?>
<table border="1" colspan="0" cellspan="0">
    <?php
        $htmldata = "";
        foreach ($new_array as $key => $value) {
          echo "<tr>";
          foreach ($value as $option) {
            echo "<td>".$option."</td>";
          }
          echo "</tr>";
        }  
    ?>
</table>

Output will be

输出将

使用PHP从上到下打印数组,而不是从左到右