Generating an 8x8 grid in PHP
Explination
Through PHP I am generating an 8x8 grid of div's. The problem is not getting this to happen (Although my methods may need to change), but rather the x and y coordinates of the blocks (stored as the id).
The Code
class Grid
{
function __construct()
{
$i = 0;
$w = 'white';
$b = 'black';
for($y=1; $y<=8; $y++)
{
for($x=1; $x<=8; $x++)
{
if($i % 2)
echo "<div class='$w' id='{$x}{$y}'></div>";
else
echo "<div class='$b' id='{$x}{$y}'></div>";
$i++;
}
echo "<br clear='all' /> \n";
$i++; //offset color for next row
}
}
}
Problem
While this class does it's job of displaying the grid, the problem is the coordinates are not how I need them. The coordinates output in the followin开发者_Python百科g fashion because of how the HTML is rendered (imagine each bracket as the div's position on the screen):
note: [x coord, y coord]
[1,1] [2,1] [3,1]
[1,2] [2,2] [3,2]
[1,3] [2,3] [3,3]
I actually need the 'reverse' of this, so that it starts at the bottom left, and the coordinates resemble that of a typical grid, ie:
[1,3] [2,3] [3,3]
[1,2] [2,2] [3,2]
[1,1] [2,1] [3,1]
I am sure there many ways to pull this off, so the answer will go to the most elegant solution, not the fastest. Thanks!
I think this is as simple as changing to:
for($y=8; $y>=1; $y--)
class Grid
{
function __construct()
{
$i = 0;
$w = 'white';
$b = 'black';
for($y=8; $y>0; $y--)
{
for($x=1; $x<=8; $x++)
{
if($i % 2)
echo "<div class='$w' id='{$x}{$y}'></div>";
else
echo "<div class='$b' id='{$x}{$y}'></div>";
$i++;
}
echo "<br clear='all' /> \n";
$i++; //offset color for next row
}
}
}
and you're done
Was looking for some code regarding grid building in PHP, used your code and changed it up...
class Grid { function __construct() { $i = 0; $w = 'white'; $b = 'black'; $y = 1; //grid size Y $y_max = 10; $x_max = 10;
while($y <= $y_max){ $x = 1; //grid size X while($x <= $x_max){ $color = ($i % 2 ? $w : $b); echo "<div class='".$color."' id='{$x}{$y}'> $x , $y </div>"; $i++; $x++; } echo "<br clear='all' /> \n"; $i++; //offset color for next row $y++; } }
}
Sorry for the formatting, I will fix the formatting later.
精彩评论