Home > database >  Output multiple rows as multiple columns
Output multiple rows as multiple columns

Time:12-02

I have a simple table and need to output the data in a way that permissions relevant to the area appear in the same row.

user   |  page    |  permission
-------------------------------
Jon    |  books   |   read
Jon    |  books   |   delete   
Jon    |  photos  |   read
Jon    |  photos  |   edit

Desired output in HTML (not a new table):

user   |   page   |  read  | edit  |  delete
-----------------------------------------------
Jon    |  books   |   X    |       |     X
Jon    |  photos  |   X    |   X   |     

Basically I need to output the data and combine all rows that have the same user and page into a single row, where permissions become columns.

echo '<table>';

foreach ($data as $row) {

    echo
    ($row['user'] == $user && $row['page'] == $page ? '' : '<tr>').'
        
        <th>'.($row['user'] == $user ? '' : $row['user']).'</th>
        <td>'.($row['page'] == $page ? '' : $row['page']).'</td>
        '.($row['permission'] == 'Create' && $row['role'] != $role && $row['page'] != $page ? '<td>x</td>' : '').'
        '.($row['permission'] == 'read' ? '<td>x</td>' : '').'
        '.($row['permission'] == 'edit' ? '<td>x</td>' : '').'
        '.($row['permission'] == 'delete' ? '<td>x</td>' : '').'
    '.($row['user'] != $user && $row['page'] != $page ? '</tr>' : '');

    $user = $row['user'];
    $page = $row['page'];
}

echo '</table>';

In theory this should work but my columns are getting extra cells added. What am I missing?

CodePudding user response:

I would preprocess that $data to be friendly for the format you want. So something like this

$sorted = array();
foreach ($data as $row) {
 if (!isset($sorted[$row['user']])) $sorted[$row['user']]=array();
 if (!isset($sorted[$row['user']][$row['page']]) $sorted[$row['user']][$row['page']] = array('read' => false, 'edit' => false, 'delete' => false);
 $sorted[$row['user']][$row['page']][$row['permission']] = true;
}

then you could loop through like

foreach ($sorted as $user => $page) {
  foreach ($page as $pagename => $perms) {
    echo "<tr><td>$user</td><td>$pagename</td>";
    foreach ($perms as $perm => $bool) {
      echo "<td>" . ($bool ? "x" : "") . "</td>";
    }
  echo "</tr>";
}
  •  Tags:  
  • php
  • Related