2016-01-06 47 views
0

我使用pp3Diso構建遊戲地圖。該庫使用字符串來確定要在每個網格單元格中使用的圖像,如下所示:01,01,01,01,01,01,01:02,01,01,01,01,01,01:01,01,01,01,01,01,01:01,01,01,01,01,01,01:01,01,01,01,01,01,01:01,01,01,01,01,01,01。 我試圖用while循環將這種類型的字符串拼湊在PHP中,但代碼在第一次迭代後似乎停止(01,01,01,01,01,01,01,01:)。我如何獲得下面的代碼來創建完整的字符串?使用PHP構建地圖網格字符串

$mapStr = ''; 

$x = 1; 
$y = 1; 

while($x <= 500){ 
    while($y <= 500){ 
     $sql = 'SELECT * FROM '.CITIES.' WHERE city_x = '.$x.' AND city_y = '.$y; 
     $result = $db->sql_query($sql); 
     $city = $db->sql_fetchrow($result); 

     if($city){ 
      $mapStr .= '02'.(($x < 500) ? ',' : ''); 
     }else{ 
      $mapStr .= '01'.(($x < 500) ? ',' : ''); 
     } 

     $y++; 
    } 

    if($x == 500){ 
     $mapStr .= ':'; 
    }else if($x == 500 && $y == 500){ 
     $mapStr .= ''; 
    } 

    $x++; 
} 

$return['map'] = $mapStr; 

此外,是否有一個更有效的方式來做到這一點,而不是查詢每個單元格的數據庫?

回答

0

原來比較容易做一個for循環:

$columns = 501; 
$rows = 501; 

for($x = 1; $x < $columns; $x++){ 
    for($y = 1; $y < $rows; $y++){ 
     $sql = 'SELECT * FROM '.CITIES.' WHERE city_x = '.$x.' AND city_y = '.$y; 
     $result = $db->sql_query($sql); 
     $city = $db->sql_fetchrow($result); 

     if($city){ 
      $mapStr .= '02'; 
     }else{ 
      $mapStr .= '01'; 
     } 

     if($y < 500){ 
      $mapStr .= ','; 
     }elseif($y == 500){ 
      $mapStr .= ':<br />'; 
     } 
    } 

    $sql = 'SELECT * FROM '.CITIES.' WHERE city_x = '.$x.' AND city_y = '.$y; 
    $result = $db->sql_query($sql); 
    $city = $db->sql_fetchrow($result); 

    if($city){ 
     $mapStr .= '02'; 
    }else{ 
     $mapStr .= '01'; 
    } 

    if($y < 500){ 
     $mapStr .= ','; 
    }elseif($y == 500){ 
     $mapStr .= ':<br />'; 
    } 
} 
echo $mapStr;