Re: splitting list into columns [message #183525 is a reply to message #183468] |
Wed, 30 October 2013 00:34 |
Christoph Michael Bec
Messages: 207 Registered: June 2013
Karma:
|
Senior Member |
|
|
Thomas 'PointedEars' Lahn wrote:
> Christoph Michael Becker wrote:
>
>> However, this algorithm will emit the table in Z-order. I wonder if
>> there is an equally elegant solution for N-order.
>
> I presume you mean this:
>
> /**
> * Returns the transpose of a two-dimensional array.
> *
> * NOTE: Does not preserve the indexes.
> *
> * @author Codler
> * @param array $a
> * @return array
> * @see http://stackoverflow.com/a/3423692/855543
> */
> function array_transpose ($a)
> {
> array_unshift($a, null);
> return call_user_func_array('array_map', $a);
> }
>
> echo '<table>'
> . '<tr>'
> . implode('</tr><tr>',
> array_map(
> function ($e) {
> return '<td>' . implode('</td><td>', $e) . '</td>';
> },
> array_transpose(array_chunk($values, $rows))
> )
> )
> . '</tr>'
> . '</table>';
>
> You can additionally use array_map('array_slice', …) to limit the number of
> columns :)
Great, thank you very much. I was not aware that array_map(null, ...)
implements the zip function as know from functional programming
languages (and even then, I might not have found this elegant solution).
The return statement of array_transpose() could be written even more
elegantly in PHP 5.6, if argument unpacking[1] will be implemented:
return array_map(...$a);
[1] <https://wiki.php.net/rfc/argument_unpacking>
--
Christoph M. Becker
|
|
|