2013-10-03 24 views
2

我試圖在PHP中寫出一個寫出表的函數,並在數據庫中查找以查找哪些單元格應具有信息。網格將始終是相同的大小,但內容可能在不同的地方。我如何在PHP中使用正確的單元格

我已經知道它能夠查看數據庫,但它似乎只突出顯示第一個單元格,而不是正確的座標。

require("sql.php"); 
$sql = <<<SQL 
    SELECT * 
    FROM `maps` 
    WHERE `objpresent` = 1 
    SQL; 

if(!$result = $db->query($sql)){ 
    die('There was an error running the query [' . $db->error . ']'); 
} // ran the query 
$xobj = array(); 
$yobj = array(); 
while($row = $result->fetch_assoc()){ 
    //echo $row['x'] . $row['y'] . $row['object'] . '<br />'; 
    $xobj[] += $row['x']; 
    $yobj[] += $row['y']; 

}// get the rows 

//find whether the row is obstructed 
for($a=0; $a<=20-1; $a++) //rows (y) 
    { 
    for($i=0; $i<=25-1; $i++) //cols (x) 
     { 
     echo "<td>"; //between these write the apt content 
     // if (empty($xobj[$i]) || empty($yobj[$a])){ 
     // echo '0'; 
     //} //detect whether there is even a record for this space 
     if(!empty($xobj[$i])) 
      { 
      if(!empty($yobj[$a])) 
       { 
       echo $xobj[$i]; //debug 
       if($xobj[$i] == $i) 
        { 
        //echo $xobj[$i]; 
        echo "A"; 
        } 
       } 
      } 
     //echo "<td><img src='emptysym.png'></img></td>"; 
     echo "</td>"; //add textual descriptions for now, add icons later 
     } 
    echo "</tr>"; 
    } 

這是我目前(儘管相當混亂)的代碼。 如果有一列的列x說2,列y說3,那麼它應該把一個字母在(2,3。 是否可以修復這個,或者有沒有更好的方法?

回答

3

使用二維數組,它的索引是從數據庫中xy值:

$xyobj = array(); 
while($row = $result->fetch_assoc()){ 
    $xyobj[$row['x']][$row['y']] = true; 
} 

然後你的輸出循環應該是:

for ($y = 0; $y < 20; $y++) { 
    echo '<tr>'; 
    for ($x = 0; $x < 25; $x++) { 
     echo '<td>'; 
     if (isset($xyobj[$x][$y])) { 
      echo 'A'; 
     } 
     echo '</td>'; 
    } 
    echo '</tr>'; 
} 
+0

真棒非常感謝你的幫助 – ZCoder

相關問題