rapidoodle
rapidoodle

Reputation: 340

Display retrieved data from database vertically in one table

What I want is to display the retrieve datas in 1 table. But I need the table row to be limit by 10 and then transfer to another column

Example output:

data1    data11
data2    data12
data3    data13
data4    data14
data5    data15
data6    data16
data7    data17
data8    data18
data9    data19
data10   data20

Upvotes: 1

Views: 1489

Answers (3)

Eric Ping
Eric Ping

Reputation: 359

If you want to use tables:

<?php

//assuming $data is an array which already contains your data
$data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

$rowsPerColumn = 10;

$columns = ceil(count($data) / $rowsPerColumn);

echo '<table>';

for ($r = 0; $r < $rowsPerColumn; $r++)
{
    echo '<tr>';
    for ($c = 0; $c < $columns; $c++)
    {
        $cell = ($c * $rowsPerColumn) + $r;
        echo '<td>' . (isset($data[$cell]) ? $data[$cell] : '&nbsp;') . '</td>';
    }
    echo '</tr>';
}
echo '</table>';
?>

Upvotes: 2

Sean
Sean

Reputation: 12433

Instead of using a table, which is a little more challenging to get your desired format, I would recommend using divs that you can style like a table

<style>
   // create a column class with a width and float to the left
  .column {width:100px;float:left;}
</style>";

<?php
// open/create 1st column
echo "<div class='column'>\n";

// create a range for example
$range = range(1,20);

foreach($range as $r){

    // after 10 records, close the last column and open/create a new column
    if($r!=1 && $r%10==1){echo "</div>\n<div class='column'>\n";}

    // echo your data in a 'cell'
    echo "<div class='cell'>data{$r}</div>\n";
}

// close last column
echo "</div>";
?>

Upvotes: 1

Fluffeh
Fluffeh

Reputation: 33502

You can create the array of data using variable variables fairly easily I think like this:

$i=0;
$j=0;
while($result=fetch_result())
{
    $colVar='';
    for($depth=0;$depth<=$j;$depth++)
    {
        $colVar.='['.$i.']';
    }
    $outputArray{$colVar}=$result;
    $i++;
    if($i>9)
    {
        $j++;
        $i=0;
    }
}

This will create an array with indexes 0-9 for the first ten rows, then add another dimension to it for each ten rows.

If you have thiry one rows in the result the data would look like this:

$outputArray[0]=data1;
$outputArray[0][0]=data11;
$outputArray[0][0][0]=data21;
$outputArray[0][0][0][0]=data31;
$outputArray[1]=data2;
$outputArray[1][1]=data12;
$outputArray[1][1][1]=data22;
...
...
$outputArray[9]=data10;
$outputArray[9][9]=data20;
$outputArray[9][9][9]=data30;

You can then create a table neatly from the data based on the depth of the array - meaning if it is a single array, make one column, if it is two deep, make two columns and so on.

Upvotes: 1

Related Questions