Justin
Justin

Reputation: 43

PHP: Building an HTML Table from an Array with Repeated Entries

I have a database table (built from a query) that lists member (called Troop), events, start date, and end date. A member might be listed more than once in the table as they are associated with more than one event.

I want to build an HTML table that lists the member's name followed by each event they are associated with before going on to the next member, which may be a few items down in the array.

I was thinking about using aforeach() statement but could not get it to work. Any pointers on how I might accomplish this? Thanks!

while(list($Event, $Troop, $StartDate, $EndDate) = mysqli_fetch_array($result)) {
  $return=$return . "<table>";
  $return=$return . "<tr>";
  $return=$return . "<th colspan=3>" . $Troop . "</th>";
  $return=$return . "</tr>";
  $return=$return . "<tr>";
    $return=$return . "<th>Event</th>";
    $return=$return . "<th>Start Date</th>";
    $return=$return . "<th>End Date</th>";
  $return=$return . "</tr>";
        //foreach ($Troop as $thisTroop) {
        $return=$return . "<tr>";
        $return=$return . "<td>" . $Event . "</td>";
        $return=$return . "<td>" . $StartDate . "</td>";
        $return=$return . "<td>" . $EndDate . "</td>";
        $return=$return . "</tr>";
        //}
  $return=$return . "</tr>";
  $return=$return . "</table>";
}

Upvotes: 1

Views: 51

Answers (2)

Atalatlae
Atalatlae

Reputation: 159

Replace your code with this. It's necesary that the sql result is sorted by Troop.

$return = '';
$currentTroop = '';

while(list($Event, $Troop, $StartDate, $EndDate) = mysqli_fetch_array($result)) {

    if ($currentTroop != $Troop) {
        $return .= "<table>"
        ."<tr>";
        ."<th colspan=3>" . $Troop . "</th>"
        ."</tr>"
        ."<tr>"
        ."<th>Event</th>"
        ."<th>Start Date</th>"
        ."<th>End Date</th>"
        ."</tr>";
    }

    $return .= "<tr>"
    ."<td>".$Event."</td>"
    ."<td>".$StartDate."</td>"
    ."<td>".$EndDate."</td>"
    ."</tr>";

    if ($currentTroop != $Troop) {
        $return .= "</tr>"
        ."</table>";
        $currentTroop = $Troop;
    }
}

Upvotes: 1

hans
hans

Reputation: 16

Create a multi-dimensional array with keys of Troops and group every records with the same Troop. And then use foreach() to loop the array and print out the information.

Group array by subarray values

Upvotes: 0

Related Questions