Dividing results table in PHP into sub-tables

54 Views Asked by At

I am revising the question I asked before that was not clear at all. I am very much new to PHP programming. I have a table in postgres:

| gene_name | description|
| gene1     | kuku       | 
| gene1     | blabla     |
| gene2     | tralala    |

I have a search form with an option to search with the gene name or the description column and I am fetching the result and presenting it in html with the following code:


    $search_input = test_input($_GET["search_keywords"]);
     $searched_by = test_input($_GET["search_by"]);
     $query = "SELECT * FROM gene WHERE lower($searched_by) SIMILAR TO       '%".pg_escape_string(search_input)."%'

    $res = pg_query($query) or die('Query failed: ' . pg_last_error());
    
    if ($res) {
    // Printing results in HTML
    echo "<table id=\"tblAnnotations\" class=\"table annot_table\">\n<thead><tr><th>Gene</th>    <th>Term</th></tr>";
  
    while ($line = pg_fetch_array($res, null, PGSQL_ASSOC)) {
      $found_gene = $line["gene_name"];
      $found_desc = $line["description"];
            
    echo "<tr><td>$found_gene</a></td><td><td>$found_desc</td></tr>\n";
    }
    echo "</tbody>\n</table>\n";
    }
    else {
    echo "<p>No results found.</p>\n";
    }
   
    pg_free_result($res);

I want to have separate sub-tables for each gene with the header of the gene name, and I just cannot get how to do it properly.

The output i want is:

| gene_name | description|
gene1 
| gene1     | kuku       | 
| gene1     | blabla     |
gene2
| gene2     | tralala    |

I tried adding a uniquegene variable and adding a loop, that will put a header above each sub-table, but it doesn't work at all, i get an empty result, so I clearly do smth very basic wrong. Will be grateful for your help!

$uniqueGenes[] = array_unique($line["gene_name"]);
     foreach ($uniqueGenes as $uniqueGene) {
     echo "<h4>$uniqueGene</h4>";
     }   
1

There are 1 best solutions below

0
Alex On

Answering to myself ) I had to divide the array of the fetched rows to separate arrays, per gene:

$geneAnnotations = array();
// Add the annotation to the specific gene in the array
$geneAnnotations[$found_gene][] = array(
    'desc' => $found_desc,
);

And than loop over each array and print the table to html.

 // Printing results in HTML
foreach ($geneAnnotations as $geneName => $annotations) {
    echo "<button class=\"collapsible\" data-table-id=\"tblAnnotations_$geneName\" onclick=\"toggleTable('tblAnnotations_$geneName')\">$geneName</button>";
    echo "<div class=\"content\">";
    echo "<table id=\"tblAnnotations_$geneName\" class=\"table annot_table\">\n<thead><tr><th>Annotation</th></tr></thead>\n<tbody>\n";

    foreach ($annotations as $annotation) {
        echo "<tr><td>{$annotation['desc']}</td></tr>\n";
    }

    echo "</tbody>\n</table>\n";
}