Chunk and transpose a flat array into rows with a specific number of columns

Use array_chunk() to break the array up in to $cols:

$chunks = array_chunk($array, ceil(count($array) / $cols));

Which would give you:

array(array('A', 'B', 'C', 'D'), array('E', 'F', 'G'));

Then combine the values from each array where the keys match.

array_unshift($chunks, null);
$chunks = call_user_func_array('array_map', $chunks);

// array(array('A', 'E'), array('B', 'F'), array('C', 'G'), array('D', NULL))

Here’s an example

Leave a Comment