-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?

1
  • This is a very simple solution. What have you tried so far? Commented Jan 8, 2013 at 7:27

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.