开发者

PHP table creation with arrays

开发者 https://www.devze.com 2023-02-12 15:44 出处:网络
I have a table with a first column called:\"Fruit\", and a last column called: \"Total\" And any columns in between are dynamically created by the number of students.

I have a table with a first column called: "Fruit", and a last column called: "Total"

And any columns in between are dynamically created by the number of students. Below is what I'm looking to dynamically make, from what the database shows so far.

<table border="1">
  <tr>
    <th>Fruit</th>
    <th>Sally</th>
    <th>John</th>
    <th>Total</th>
  </tr>
  <tr>
    <td>apples</td>
    <td>5</td>
    <td>3</td>
    <td>8</td>
  </tr>
  <tr>
    <td>bananas</td>
    <td>3</td>
    <td>5</td>
    <td>8</td>
  </tr>
  <tr>
    <td>Oranges</td>
    <td>3</td>
    <td>3</td>
    <td>6</td>
  </tr>
  <tr>
    <td></td>
    <td>11&开发者_Go百科lt;/td>
    <td>11</td>
    <td>22</td>
  </tr>
</table>

Here's the difficulties I run into. The fruit names, students, and fruit consumed are pulled from the database. And I don't know how many fruit rows nor student columns there will be.

This is as far as I got:

<table> 
    <tr> 
        <th>Fruit</th> 
        <?php $sqlS = db("SELECT s.*, sf.consumed FROM `tbl_students` s, `tbl_students_fruit` sf WHERE s.studentid = f.studentid ORDER BY s.studentname ASC"); 
            while($student = mysql_fetch_array($sqlS)){ ?>
        <th><?php echo $student['studentname'];?></th> 
        <?php } ?> 
        <th>Total</th> 
    </tr> 


  <?php $sqlF = db("SELECT * FROM `tbl_fruit` ORDER BY fruitname ASC"); 
        while($fruit = mysql_fetch_array($sqlF)){ ?>
    <tr> 
        <td><?php echo $fruit['fruitname'];?></th> 

        <td></td> 
        <td></td>
    </tr> 
   <? } ?>

</table>

As you can see, I'm creating the Fruit rows, and Student columns. But it's incomplete. I've only created the column headers, and not the columns below the headers. From this point I am stuck on the guts of the table.

I am sure arrays are the way to go with this monstrosity. But the only way my feeble brain can make this work is to have more queries, which I'm sure is a very wrong way to do this.

If there were 3 students or 15 students, I can make them appear in the table th columns, but not in rows in their columns.

How does one traverse dynamic columns this way?

And if my demo above is confusing, I don't blame you!


well, I am assuming that your db structure is as follows:

[tbl_students]
studentid, studentname

[tbl_fruit]
fruitid, fruitname

[tbl_students_fruit]
id, fruitid, studentid, consumed

http://pastebin.com/CxPUeXR0

I haven't tested it, so good luck

0

精彩评论

暂无评论...
验证码 换一张
取 消