【问题标题】:PHP incrementing through data set [closed]PHP通过数据集递增[关闭]
【发布时间】:2013-04-21 10:30:09
【问题描述】:
    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 在数据库中对齐的结果集,但我真的不知道如何增加我正在检索的行,任何建议?

编辑:代码更新

【问题讨论】:

  • 我知道目前它最终是一个无限循环。
  • 为什么要在 for 循环中检索房间信息?有可能改变吗?为什么不在循环之外做呢?此外,您应该查看 while 条件。如果我正确理解了您的问题,那么有一系列房间,您需要找到那些具有相同 x 和 y 位置的房间,对吗?
  • 可以改变,每个建筑都有不同的示意图,你是对的,是的,while循环被打破了,但我不确定如何/为什么。
  • 为了重申问题,我需要从建筑表中拉取房间信息,房间的默认状态是空的,所以我只有两个不为空的条目,但坐标是不同的。我需要输出“房间”、“空白”、“空白”、“房间”,其中房间等于循环 x 和 y。
  • ^ 是的,我暂时在开发服务器上删除了它,它确实会永远运行,因为我不明白如何递增到下一个结果集。

标签: php arrays for-loop mysqli


【解决方案1】:

试试这个。我拿走了你的房间,把它带到了循环之外。然后我生成了一张房间坐标图。这样,您只需遍历房间一次,而不是对网格的每一行和每一列都执行一次。

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

$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
        }
    }
}

【讨论】:

  • 效果很好,有时您只需要一个全新的视角。谢谢:D
  • 不客气。 :)
猜你喜欢
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
相关资源
最近更新 更多