Atexo
Atexo

Reputation: 31

Creating a html Table based on transposed Joomla data

I'm struggling to create a table made of the joomla database. Currently I'm using the following code:

$query= "SELECT DATUM, A , B ,C, D, E, F, G FROM ".$db->quoteName('#__XYZTABLE'). " WHERE DATUM_ENG>= CURDATE()";
$db->setQuery($query);
$results = $db -> loadObjectList();
    echo "<table><tr><th>Name</th><th>Department</th></tr>";

foreach($results as $row){

echo "<tr>"; echo "<td>".$row->last_name."</td>";

echo "<td>".$row->dept."</td>";

echo "</tr>"; }

echo "</table>";

Basically, this code works fine. The result is:

DATUM , A , B ,C, D, E, F, G 
xxxx1 ,aa1,bb1,cc1,dd1,ee1,ff1,gg1
xxxx2 ,aa2,bb2,cc2,dd2,ee2,ff2,gg2
....

However, I want to create an html table which transposes the data and shows it like the following form:

    xxxx1 , xxxx2, xxxx3 ....
A   aa1   , aa2  , aa3
B   bb1   , bb2  ,bb3
C   cc1   , cc2  ,cc3
D   .....

After searching in this forum and Google, I wasn't able to find anything similar. Can someone help me with a specific code?

Upvotes: 3

Views: 96

Answers (1)

Tom Kuschel
Tom Kuschel

Reputation: 765

Using some php array functions, you may take this:

$object = new stdClass();
// create some test values
$object->DATUM = '2016120';
$object->A = 'aa';
$object->B = 'bb';
$object->C = 'cc';
$object->D = 'dd';
$object->E = 'ee';
$object->F = 'ff';
$object->G = 'gg';

for ($i = 1; $i < 10; $i++){
    $vars = get_object_vars($object);
    $obj = new stdClass;
    foreach ($vars as $key=>$var){
        $obj->$key = $var.$i;
    }
    $results[] = $obj;
}
// end of creating test values

echo "<table><tr><th>DATUM</th><th>A</th><th>B</th><th>C</th><th>D</th></tr>";

foreach ( $results as $row ) {
    echo "<tr>";
    echo "<td>" . $row->DATUM . "</td>";
    echo "<td>" . $row->A . "</td>";
    echo "<td>" . $row->B . "</td>";
    echo "<td>" . $row->C . "</td>";
    echo "<td>" . $row->D . "</td>";
    echo "<td>" . $row->E . "</td>";
    echo "<td>" . $row->F . "</td>";
    echo "<td>" . $row->G . "</td>";
    echo "</tr>";
}
echo "</table>";

echo '<h3>New Variant</h3>';
echo '<table>';
$elements = count($results);
foreach (get_object_vars($results[0]) as $key=>$var){
    echo '<tr>';
    $tag = ($key === 'DATUM') ? 'th>' : 'td>';
    echo '<'.$tag . $key .'</'.$tag;
    for ($i = 0; $i < $elements; $i++){
        echo '<'.$tag . $results[$i]->$key.'</'.$tag;
    }
    echo '</tr>';
}
echo '</table>';`

Upvotes: 1

Related Questions