Re: Sepating MySQL result set into html tables

From: Date: Sat, 27 Sep 2008 08:47:41 +0000
Subject: Re: Sepating MySQL result set into html tables
References: 1 2 3 4 5  Groups: php.general 
Request: Send a blank email to php-general+get-281024@lists.php.net to get a copy of this message
O/H Robert Cummings ??????:
On Fri, 2008-09-26 at 14:41 -0400, Robert Cummings wrote:
On Fri, 2008-09-26 at 21:23 +0300, Thodoris wrote:
    
On Fri, 2008-09-26 at 13:50 -0400, admin@buskirkgraphics.com wrote:
Might I suggest you count the fields and divide it by the cols you want to display? Example
$forest = mysql_query("SELECT * FROM your_table"); $gump = mysql_num_fields($forest);
              
First of all the problem is with the rows not the columns. The problem is that I want to divide the rows into equal (or anything close to that) chunks and put every chunk in a separate table. There I said it :-) .
      
Because I know my table contains 15 rows I can do this.
$tulip = floor($gump /5);
                        You can count the rows (not the cols) in the result set but you can't base your algorithm on that only.
The problem is that if for e.g. you have 91 rows and you want to divide it into 3 you will have three chunks of 30 like this: 30, 30, 31
      
You have a bug if you have 16 rows.
In my case I really don't care in what table the extra row goes. The solution is pretty easy, I just don't have time right now to write
it for you. Either way, I would approach the problem inverseley to your current solution. Instead of traversing the rows and performing internal calculations, I'd calculate the tables and rows needed and then traverse that information and in the innermost loop traverse the result set using the next() function.
    
<?php $cells = array( 'First', 'Second' ); $items = array( array( 'one', 'two' ), array( 'one', 'two' ), array( 'one', 'two' ), array( 'one', 'two' ), array( 'one', 'two' ), arr $numTables = 3; $items = array_chunk( $items, ceil( count( $items ) / $numTables ) ); $html = ''; foreach( $items as $tableItems ) {
    if( $tableItems )
    {
        $html .= '<table><tr>';
        foreach( $cells as $cell )
        {
            $html .= '<td>'.$cell.'</td>';
        }
        $html .= '</tr>';
        foreach( $tableItems as $rowItems )
        {
            $html .= '<tr>';
            foreach( $rowItems as $item )
            {
                $html .= '<td>'.$item.'</td>';
            }
            $html .= '</tr>';
        }
        $html .= '</table>';
    }
} ?> I changed my mind on how I wanted to do it. Either way... simple enough :) Adapt to fit your own scenario. Cheers, Rob. Thanks guys for all the responses. Especially Rob showed me the magical use of the array_chunk function which I was tending to ignore :-) . ------- Thodoris

« previous php.general (#281024) next »