Display multilevel associative array in table form

The following is an example of an array that I would like to display:

Array ( [Media] => Array ( [2012-12-10] => Array ( [Mentor] => Evan Tobin [Veteran Member] => James ) [2012-12-21] => Array ( [Mentor] => Evan Tobin ) ) [Website] => Array ( [2012-12-10] => Array ( [Mentor] => Evan Tobin ) [2012-12-21] => Array ( [Mentor] => Evan Tobin ) ) ) 

So, you can see that he has several teams, and each team has several dates that they meet, and every day there will be different people with different tasks. Using this table, I would like it to display as such:

 Media Team Role || 2012-12-10 || 2012-12-21 Mentor || Evan Tobin || Evan Tobin Veteran Member || James || 

I tried using foreach instructions, but I get too much as soon as I get further. Any help is greatly appreciated.

+4
source share
1 answer

Here you are:

 <?php // [your array] $tabledata = array( 'Media' => array( '2012-12-10' => array( 'Mentor' => 'Evan Tobin', 'Veteran Member' => 'James' ), '2012-12-21' => array( 'Mentor' => 'Evan Tobin' ) ), 'Website' => array( '2012-12-10' => array( 'Mentor' => 'Evan Tobin' ), '2012-12-21' => array( 'Mentor' => 'Evan Tobin' ) ) ); // [/your array] // [the tables] echo '<table border="1">'; foreach($tabledata as $teamkey => $teamval){ // [helper] $dates = array(); $roles = array(); foreach($teamval as $datekey => $dateval) { if (!in_array($datekey, $dates)) { $dates[] = $datekey; } foreach($dateval as $rolekey=>$roleval) { if (!in_array($rolekey, $roles)) { $roles[] = $rolekey; } } } // [/helper] // [team name] >> row 1 echo '<tr>'; echo '<th align="left" colspan="'.(sizeof($dates)+1).'">'.$teamkey.' Team</th>'; echo '</tr>'; // [/team name] // [role column and date column] >> row 2 echo '<tr>'; echo '<td>Role</td>'; foreach($dates as $date) { echo '<td>'.$date.'</td>'; } echo '</tr>'; // [/role column and date column] // [role and team member for each date] >> row 3, 4, 5, ... n foreach($roles as $role) { echo '<tr>'; echo '<td>'.$role.'</td>'; foreach($dates as $date) { echo '<td>'; if (isset($teamval[$date][$role])) { echo $teamval[$date][$role]; // team member name } else { echo '&nbsp;'; // insert blank space for cross browser support } echo '</td>'; } echo '</tr>'; } // [/role and team member for each date] } echo '</table>'; // [/the tables] 

If you need separate tables for each command, you can put them in a loop.

Hope this helps.

+2
source

All Articles