-1

Currently I have a PHP 3 level array. How do I display it in a table form? Using print_r I could display out the full array but I need to beautify it to show in a table form. Is it possible?

Sample of the array to be inserted is as shown in another posting: PHP foreach with Nested Array?

Community
  • 1
  • 1
aandroidtest
  • 1,493
  • 8
  • 41
  • 68

2 Answers2

1

So... each level of the array should be an embedded table?

<table>
    <?php // FIRST LEVEL
    foreach ($myArray as $first_level): ?>
    <tr>
        <td>The header of the first level, here's some data <?php echo $first_level['some_data']; ?></td>
    </tr>
    <tr>
        <td>
            <table>
            <?php // SECOND LEVEL
                foreach($first_level['second_level'] as $second_level): ?>
                    <tr>
                        <td><?php echo $second_level['some_data']; ?></td>
                    </tr>
            <?php endforeach; ?>
                </table>
        </td>
    </tr>
    <?php endforeach; ?>
</table>

..and keep repeating the pattern

Atticus
  • 6,585
  • 10
  • 35
  • 57
1

So many ways to do it, even more so since you didn't provide a template for the output format ....
Let's assume each element $e of the input array $src stands for one row in the table.
Then $e[0] is the string element (one, two, three) and $e[1] is the corresponding array 1,2,3, 4,5,6 or 7,8,9.
Let's put $e[0] into <th>...</th> elements.

foreach( $src as $e ) {
  echo '<th>', $e[0], '</th>';
}

and then wrap each element in $e[1] in <td>....</td>.

foreach( $src as $e ) {
  echo '<th>', $e[0], '</th>';
  foreach($e[1] as $v) {
    echo '<td>', $v, '</td>';
  }
}

now wrap that into another <tr>...</tr> and you are done

foreach( $src as $e ) {
  echo '<tr>';
  echo '<th>', $e[0], '</th>';
  foreach($e[1] as $v) {
    echo '<td>', $v, '</td>';
  }
  echo "</tr>\r\n";
}

the same thing a bit shorter (see http://docs.php.net/join)

<?php
$src = getData();
foreach( $src as $e ) {
    echo '<tr><th>', $e[0], '</th><td>', join('</td><td>', $e[1]), "</td></tr>\n";
}

function getData() {
    return array(
        array( 'one', array(1,2,3) ),
        array( 'two', array(4,5,6) ),
        array( 'three', array(7,8,9) )
    );
}

the output is

<tr><th>one</th><td>1</td><td>2</td><td>3</td></tr>
<tr><th>two</th><td>4</td><td>5</td><td>6</td></tr>
<tr><th>three</th><td>7</td><td>8</td><td>9</td></tr>

see also: http://docs.php.net/htmlspecialchars

VolkerK
  • 95,432
  • 20
  • 163
  • 226