newbie_girl newbie_girl - 1 month ago 5
PHP Question

How to return combinations of coordinates in PHP?

I would like to return combination of coordinates. Please take a look at the provided script and question below.

This script

<?php
$x = 1;
$y = 8;
$x_c = -200;
$y_c = 100;
$i = 20;
while($x <= 5) {
echo "x is: $x <br>";
echo "x_c is: $x_c <br>";
$x++;
$x_c = $x_c + $i;
}
echo "<hr>";
while($y <= 13) {
echo "y is: $y <br>";
echo "y_c is: $y_c <br>";
$y++;
$y_c = $y_c - $i;
}
?>


will return:

x is: 1
x_c is: -200
x is: 2
x_c is: -180
x is: 3
x_c is: -160
x is: 4
x_c is: -140
x is: 5
x_c is: -120
y is: 8
y_c is: 100
y is: 9
y_c is: 80
y is: 10
y_c is: 60
y is: 11
y_c is: 40
y is: 12
y_c is: 20
y is: 13
y_c is: 0


Question

How can I return combination of this as pattern

x1,y1,x_c1,y_c1
x1,y2,x_c1,y_c2
x1,y3,x_c1,y_c3
...
x2,y1,x_c2,y_c1
x2,y2,x_c2,y_c2
x2,y3,x_c2,y_c3
...
x3,y1,x_c3,y_c1
x3,y2,x_c3,y_c2
x3,y3,x_c3,y_c3


or with numbers

1,8,-200,100
1,9,-200,80
1,10,-200,60
...
2,8,-180,100
2,9,-180,80
2,10,-180,60
...
3,8,-160,100
3,9,-160,80
3,10,-160,60

Answer

You need to put the $y loop inside the $x loop. Here I am using $yy and $yy_c for the inner loop so that I can reset them back to the original $y and $y_c before entering the loop.

<?php
$x = 1;
$y = 8;
$x_c = -200;
$y_c = 100;
$i = 20;
while($x <= 5) {
    $yy = $y;
    $yy_c = $y_c;
    while($yy <= 13) {
        echo "$x,$yy,$x_c,$yy_c<br>";
        $yy++;
        $yy_c = $yy_c - $i;
    } 
    $x++;
    $x_c = $x_c + $i;
}
?>
Comments