1

I have table of data that store number into the rows. Now I wanna to create table with them. I want to crate X rows and Y columns. I know I should use while or foreach loop but I don't know how... :(

$result = $db->query(
        "SELECT `x`,`y`,`noe` FROM `table` "
      . "WHERE (`x` >= 0 and `x` < 4) and (`y` >= 0 and `y` < 4) "
      . "ORDER BY `x`,`y` ASC") or die($db->error);

if($result) {
    echo "<pre>",$result->num_rows,"</pre>";
    echo "<pre>",  print_r($row = $result->fetch_object()),"</pre>";
?>
<table>

<?php
    while($row = $result->fetch_all()){
        //echo "X: ", $row->x, " ,Y: ", $row->y," ,Type of item: ", $row->noe,"<br>";
        echo '<tr><td>',$row->x,'-',$row->y,'</td></tr>';
    }
}
?>
</table>    
2

1 Answer 1

1

It's an interesting question. If you had a two-dimensional array, you're right you would loop over x first and then over each y for a given value of x. However your data, although it describes a two-dimensional structure, comes in a flat result. I'd loop over the rows, keep track of the last x and create new <tr>..</tr> every time you notice the x in your result is different from the one in the last iteration (ie the row has changed).

Something like

$lastx = -1; // or some value you know you'll never use
while ($row = $result->fetch_all()) {
  $x = $row['x'];
  if ($x != $lastx) {
     echo '<tr>';
  }
  echo '<td>...</td>'
  if ($x != $lastx) {
    echo '</tr>';
    $lastx = $x;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

i want to create something like this: uploadco.ir/uploads/ohxpfv53d09fx445odoj.png

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.