I have an array of objects, containing lists of times. I have to stick this in a Matrix-alike array, in order to put it in a table. This is a part of my earlier SO question on how to build calendar tables
$node->sessions = array(
1286452800, // '2010-10-07 14:00:00'
1286460000, // '2010-10-07 16:00:00'
);
$node->title = 'Foo';
$nodes[1] = $node;
$node->sessions = array(
1286452800, // '2010-10-07 14:00:00'
1286460000, // '2010-10-07 16:00:00'
1286461800, // '2010-10-07 16:30:00'
);
$node->title = 'Bar';
$nodes[2] = $node;
$node->sessions = array(
1286460000, // '2010-10-07 16:00:00'
1286461800, // '2010-10-07 16:30:00'
1286465400, // '2010-10-07 17:30:00'
);
$node->title = 'Baz';
$nodes[3] = $node;
These represent a table of playdates of movies. As can be seen in action here. The code for this, right now is far too complex (IMHO) and could be simplified, just that I don't know how. Maybe trough some Matrix-library? Or some algorythm that I am unaware of?
The resulting structure, should be an array representing the header (column names of the table) and an array-with-arrays representing the rows. As follows:
$header = array(
' ', // empty "cell"
ttt, // ttt being the timestamp for '14:00'
uuu, // idem for '15:00'
vvv, // idem for '16:00'
www, // idem '17:00'
);
// title, 14:00, 15:00, 16:00, 17:00
$rows = array(
array(
'Bar', 1286452800, '', array(1286460000, 1286461800), '', //Both 16:00 and 16:30 grouped under 16:00 'header'
),
array(
'Baz', '', '', array(1286460000, 1286461800), 1286465400
),
array(
'Foo', 1286452800, '', 1286460000, '',
)
);
Each row should have the same amount of "cells". Timestamps should be grouped under the hour they belong to (16:15, 16:30 etc all grouped under 16:00) Also note that the above-given output structure might be optimised too, please let me know if there are ways to simplify the code, by simplifying or changing the resulting "matrix".
Pseudocode for what I do now:
- usort $nodes by title
- loop over all the $nodes to find the width of the matrix (14:00 to 17:00) and fill the
$header
- loop over all the $nodes again, for each node loop over $header and fill an array with either empties
('')
or with the timestamps.
Now, for a the three entries above, that is not a big problem, but this matrix can grow very wide (large $headers array) and deep (many $nodes) resulting in a lot of duplicate looping. But performance and duplicate looping is not my greatest concern, mostly having cleaner and less nested, less complex code, is. :)