Re: splitting list into columns [message #183462 is a reply to message #183455] |
Sun, 27 October 2013 16:42 |
Christoph Michael Bec
Messages: 207 Registered: June 2013
Karma:
|
Senior Member |
|
|
Thomas 'PointedEars' Lahn wrote:
> Christoph Michael Becker wrote:
>
>> richard wrote:
>>> I want to display the 200 item list into 5 columns.
>>> What I have now works, except that the 2 to 5th columns are not adding
>>> properly.
>>> What do I need to change to make it work right?
>>
>> To create a table from a 1-dimensional indexed array $values in N-order,
>> you may use the following outline:
>>
>> $rows = 40;
>> $cols = 5;
>> echo '<table>';
>> for ($i = 0; $i < $rows; ++$i) {
>> echo '<tr>';
>> for ($j = 0; $j < $cols; ++$j) {
>> echo '<td>';
>> $n = $j * $rows + $i;
>> echo $values[$n];
>> echo '</td>';
>> }
>> echo '</tr>';
>> }
>> echo '</table>';
>
> Or you could use
>
> echo '<table>'
> . '<tr>'
> . implode('</tr><tr>',
> array_map(
> function ($e) {
> return '<td>' . implode('</td><td>', $e) . '</td>';
> },
> array_chunk($values, $cols)
> )
> )
> . '</tr>'
> . '</table>';
>
> and additionally use array_slice() if you wanted to limit the output to
> $rows rows :)
That is a nice solution (the applicative programming paradigm is so
elegant; unfortunately, I'm still not much used to it). :)
However, this algorithm will emit the table in Z-order. I wonder if
there is an equally elegant solution for N-order.
> See also:
>
> <http://php.net/array_chunk>
>
> (the exploit or false entry apparently has disappeared; Chromium no longer
> warns about php.net)
Some explanation about what has happened can be found on
<http://php.net/archive/2013.php#id2013-10-24-2>.
--
Christoph M. Becker
|
|
|