My wife and I are traveling over the next 2 months, and as an exercise I created a page to let our families and friends know our location (roughly).
The result is quite neat, and I’ll explain a few of the finer points.
The Javascript Flipping Clock is a direct borrow from a NetTuts tutorial. Javascript wizard I ain’t, but it looks pretty swell.
The current activities are stored in one array per activity for a total of 6. To determine which array to pull from, I did a fairly straight forward elseif tree:
22 23 24 25 26 27 28 29 30 31 32 33 34 35 | $array_to_use = ''; //always initialize if ($now < 1258783201) { $array_to_use = $boston; } elseif (1258783201 < $now && $now < 1258956001 ) { $array_to_use = $driving; } //many other elseif else { $array_to_use = $default; //in case the page is viewed later } $quote = $array_to_use[rand(0,count($array_to_use)-1)]; //picks one from the array |
Some key points are highlighted, and these lead to robust code: Always initialize your variables and provide default values. There’s a potentially confusing part at the end to choose the actual phrase to display.
To access an array element, you provide it with an index. The first element in $Array is $Array[0], for example. This uses several nested functions. First it counts the elements in $array_to_use and subtracts 1 (to make the first element = 0). Then it picks a random number from 0-(# of elements in array), and uses that as the index for the array. The result is that each time to access the page, it shows a pseudo-random phrase.
The timeline was all displayed using CSS and HTML. It’s hard to be semantic for something so abstract, but the code is there for your inspection. There was a fair amount of math to ensure the chart was actually to scale, and I believe I wound up at roughly 8px per day. The final bit was making the yellow indicator move (slowly) as time passed. The HTML is a fairly straightforward
118 | <div id="ticker" style="left:<?php echo $diff;?>px;"></div> |
$Diff is calculated by some subtraction and scaling of times, like so:
5 6 7 | $start = 1258092001; //midnight start date $now = time() + 3600; //plus an hour for EST $diff = round(($now-$start)/10800); //division puts it in the 3hrs/pixel range |
This is a good demonstration of some basic PHP scripting. Let me know if you have any questions about it.
