javascript datatables and subrows within PHP/HTML table

40 views Asked by At

The code below outputs data by grouping rows that have same pr_id within subrows. I tried to use datatable to enable filtering/searching/export, but it is not working. The page displayed is not what I am expecting. For example, I expect:

################################
pr_Id # Name #  Organism # Vel
################################
id1  # pr1   # homo sapiens# 100
    # pr2   # homo sapiens # 200
    # pr3   # homo sapiens # 200
################################
id2 # pr1   # mus musculus # 10
#############################

I get:

################################
pr_Id # Name #  Organism # Vel
################################
id1  # pr1   # homo sapiens# 100
    # id1  # pr2        # homo sapiens
    #     # id1        # pr3
################################
id2 # pr1   # mus musculus # 10
#############################

It seems like the data having same pr_id gets shifted. Looking at the doc, it does not seem that js datatable can handle rowspan within tables. Is there a way to overcome this limitation ? Or is there an alternative as efficient as datatable that one can use in this case ?

// Retrieve the data from the database 
$sql = "SELECT pr_id, name, velocity, organism 
       FROM EP 
       ORDER BY pr_id";
   
   

$results = $db->query($sql)->fetchAll();

// Create an associative array to store the grouped results
$groupedResults = array();

// Group the results by pr_id
foreach ($results as $row) {
   $pr_id = $row['pr_id'];

   // Check if the pr_id exists as a key in the groupedResults array
   if (isset($groupedResults[$pr_id])) {
       $groupedResults[$pr_id][] = $row; // Append the row to the existing pr_id key
   } else {
       $groupedResults[$pr_id] = array($row); // Create a new key with the pr_id and assign the row
   }
}

foreach ($groupedResults as $pr_id => $groupedRows) {
   $rowSpan = count($groupedRows);

   foreach ($groupedRows as $row) {
       echo "<tr> ";
       
       // Output the first column with the pr_id and rowspan for subrows
       if ($currentRow === 0) {
           echo "<td rowspan='$rowSpan'>$pr_id</td>";
       }

  

       print "<td>".$row['name']."</td>";
       print "<td>".$row['organism']."</td>";

// .... etc
}
}
   
<script>
$(document).ready(function() {
   $('#myTable').DataTable({

      
   });
});


</script>
0

There are 0 answers