PHP通过数据集递增

时间:2013-04-27 08:51:42

标签: php arrays for-loop mysqli

    global $mysqli;
    $building = $position['buildingID'];     
    if($level == 'room') {

        // Get building size 
        $buildingQuery = "SELECT * FROM buildings WHERE buildingID = '$building'";
        $buildingArea = $mysqli->query($buildingQuery) or die(mysqli_error($mysqli));
        $Area = $buildingArea->fetch_array(MYSQLI_ASSOC);
        $AreaX = $Area['areaX'];
        $AreaY = $Area['areaY'];

        $sql = "SELECT * FROM rooms WHERE buildingID = '$building'";
        $result = $mysqli->query($sql) or die(mysqli_error($mysqli));
        $rooms = $result->fetch_array(MYSQLI_ASSOC);

        for($y = 0; $y <= $AreaY; $y++){
            for($x = 0; $x <= $AreaX; $x++) {
                //See if room exists for coordinates
                    if(($rooms['position_x'] == $x) && ($rooms['position_y'] == $y)
                        && ($position['room_x'] == $x) && ($position['room_y'] == $y)) {
                        echo '<img src="../../resources/images/inroom.php" id="'.$x.'_'.$y.'" />';
                        echo ' ';
                    } else if (($rooms['position_x'] == $x) && ($rooms['position_y'] == $y)) {
                            echo '<img src="../../resources/images/inroom.php" id="'.$x.'_'.$y.'" />';
                            echo ' ';
                    } else {
                        echo "(".$x.","." ".$y.")";
                        if ($x == $AreaX) {
                            echo '<br />'; 
                        }
                    }
            }
        }
    }
}

基本上问题是我有一个网格系统,我需要显示结果集,其中坐标X和Y在数据库中对齐,但我真的不知道如何递增我正在检索的行,任何建议?

编辑:代码更新

1 个答案:

答案 0 :(得分:0)

试试这个。我拿起你的房间把它带到了环路外面。然后我生成了一个房间坐标图。这样,您只需要在房间中循环一次,而不是为网格的每一行和每列进行循环。

然后将其四舍五入,迭代网格并检查坐标是否在地图中。如果他们是我们找到了一个房间,否则我们发现了一个空白。

$rooms = $result->fetch_array(MYSQLI_ASSOC);

$map = array();

foreach($rooms as $room)
{
    $position_x = $room['position_x'];
    $position_y = $room['position_y'];
    $map[$position_x][$position_y] = $room;
}

for($y=0;$y<=$AreaY;$y++)
{
    for($x = 0; $x <= $AreaX; $x++) 
    {
        if(isset($map[$x][$y]))
        {
            // room
        }
        else {
            // blank
        }
    }
}