-4

I am trying to output an array as an html table, a sample of the array is..

Array
(
    [18] => Array
        (
            [colour] => red
            [size] => large
            [age] => 220
        )
        [19] => Array
        (
            [colour] => yellow
            [size] => small
            [age] => 20
        )
        [12] => Array
        (
            [colour] => brown
            [size] => large
            [age] => 2
        )
)

I am ok with doing a foreach for a simple array but does anyone have an example showing this being converted into a table for this type of array?

7
  • 3
    A table? Like any table? You don't have any requirements more specific than that? Here you go: <table><tr><td>I'm a table!</td></tr></table>. (Do at least make an effort to solve this problem, it helps clarify your intent and shows you're committed to solving it.) Commented Aug 21, 2017 at 15:26
  • 1
    @tadman you know your HTML quite well ;-) basic 101 stuff. Commented Aug 21, 2017 at 15:27
  • 2
    @Fred-ii- Experts Exchange Level A+++ Certified HTML Ph.D! (Fought the urge to add <tbody>) Commented Aug 21, 2017 at 15:27
  • 1
    Possible duplicate of How to create a HTML Table from a PHP array? - Googling PHP array to table yielded me about 3,450,000 results Commented Aug 21, 2017 at 15:29
  • 1
    "I am ok with doing a foreach" - Then have you tried? "being converted into a table for this type of array" - And what 'type of array' is this? Is there some reason a foreach wouldn't iterate over this array? I guess it's not really clear to me where you're actually stuck here. Commented Aug 21, 2017 at 15:30

1 Answer 1

4

Try something like this:

$data = //your array
$html = "<table>";
foreach($data as $row) {
    $html .= "<tr>";
    foreach ($row as $cell) {
        $html .= "<td>" . $cell . "</td>";
    }
    $html .= "</tr>";
}
$html .= "</table>";

Your question is extremenly vague so this is a vague answer, but you should get the general idea :P

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

2 Comments

Concatenation: += !== .=
Ah yeh my bad, changing now.

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.