9

I am trying to print a table using PHP/HTML. Data stored inside array like this:

Array ( [id] => 1 [first_name] => mike [last_name] => lastname )

My code is as follow. It runs and there are no error however the output is not as expected. Here is the PHP/HTML code:

<table>

<tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
</tr>

<?php foreach ($res as $item): ?>
<tr>
     <td><?php echo $item['id'] ?></td>
     <td><?php echo $item['first_name'] ?></td>
     <td><?php echo $item['last_name'] ?></td>
</tr>
<?php endforeach; ?>

</table>

The result I get is the first character of the items:

1       2      3
1       1      1
m       m      m
l       l      l

Not sure what I am doing wrong? I would really appreciate an explanation.

UPDATE:

PHP CODE that has no errors:

<?php 
    foreach ($result as $row) 
    { 
        echo '<tr>';
        echo '<td>' . $row['id'] . '</td>';
        echo '<td>' . $row['first_name'] . '</td>';
        echo '<td>' . $row['last_name'] . '</td>';
        echo '</tr>';
    }
?>

And this is my array with only one "row" in it:

Output of $result variable using print_r($result) wrapped with < PRE > tags

Array
(
    [id] => 3
    [first_name] => Jim
    [last_name] => Dude
)

Here is the result I am getting:

Actual Table result:

ID    First Name  Last Name
3     3           3
J     J           J
D     D           D

However if I have 0 in array or more than 1 (meaning 2 or more) it works perfectly. IT JUST DOES NOT WORK WHEN I HAVE ONLY ONE "ROW" OF ELEMENTS INSIDE ARRAY. For example this array, works perfectly:

  Array
    (
    [0] => Array
        (
            [id] => 3
            [first_name] => Jim
            [last_name] => Dude
        )

    [1] => Array
        (
            [id] => 4
            [first_name] => John
            [last_name] => Dude2
        )
    )

I get this result:

ID      First Name    Last Name
3       Jim         Dude
4       John            Dude2

I am not really sure what I am doing wrong. The idea is not knowing how many items is in a Table read it into $result variable and then using this variable print all elements inside HTML table. Table could contain O elements, 1 row of elements, 1 or more rows of elements.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    N-level array into table has answered here https://stackoverflow.com/questions/4746079/how-to-create-a-html-table-from-a-php-array/47015800#47015800 – Delickate Oct 30 '17 at 13:14
  • This thread has been answered here [Click here](https://stackoverflow.com/questions/4746079/how-to-create-a-html-table-from-a-php-array/47068295#47068295) – Delickate Nov 02 '17 at 05:45

9 Answers9

4

Do not remove your foreach loop. Without seeing your code where you build your array, my guess would be you are doing this:

$res = array('id' => 1, 'first_name'=>'mike', 'last_name'=>'lastname');

when in fact what you probably want to be doing is this:

$res[] = array('id' => 1, 'first_name'=>'mike', 'last_name'=>'lastname');

the brackets [ ] add an array of all the values to your array. This way you can loop through each as a collection of values, not individual values.

David Stetler
  • 1,465
  • 10
  • 14
3

You data structure is not matrix but an array:

Array ( [id] => 1 [first_name] => mike [last_name] => lastname )

You need something like this to do what you want:

Array(
    [0] => Array ( [id] => 1 [first_name] => mike [last_name] => lastname ),
    [1] => Array ( [id] => 1 [first_name] => mike [last_name] => lastname )
    ........
);

Apart from that, code seems fine...

Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85
  • I removed foreach from there and now it does display items correctly. I am just not sure if like you mention in your case I have more "rows" how will I move to the next one without foreach? And what happens if my program has an array with only one "row"? –  Dec 26 '12 at 23:07
  • Well, it is critical issue here to generate you data structure properly. You need to answer following questions: "Do I expect multiple rows?", "Do I expect no rows at all?" or even "Do I expect single row every time?". In case you will have multiple rows you **will** need `for`/`foreach` loop. Allow me to be more concrete here, and ask what are you trying to build? – Jovan Perovic Dec 26 '12 at 23:15
2
<? Php
echo "<table border="2">";

foreach($ array as $ values)
{

echo "<tr><td>";

echo "$ values";

echo "</td></tr>";
}

?>

I wrote this for printing single array values into a table

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
phani
  • 21
  • 2
1

This is how I solved a similar problem I had with my webpage. I wanted the page to display an array of all classes a specific teacher teaches using session variables. I hope that, even though the subject might not be relevant to you, the general gist will help people out.

<?php 

    echo "<table border='1' style='border-collapse: 
    collapse;border-color: silver;'>";  
    echo "<tr style='font-weight: bold;'>";  
    echo "<td width='150' align='center'>Class</td>";  
    echo "</tr>";

    foreach ($query_class_array as $row) 
     { 
      echo '<td width="150" align=center>' . $row['Class'] . '</td>';
      echo '</tr>';
     }
?>
Sean Limpens
  • 79
  • 1
  • 1
  • 12
1

If the array is of std object type, you can't use [], instead use -> to get specific entities

<!DOCTYPE html>
<html>
<body>
<table>

<tr>
    <th>id</th>
    <th>First name</th>
    <th>Last name</th>
    <th>email</th>
    </tr>

<?php 

foreach($data as $item) {?>

<tr>
     <td><?php echo $item->id; ?></td>
     <td><?php echo $item->first_name; ?></td>
     <td><?php echo $item->last_name ;?></td>
     <td><?php echo $item->email;?></td>

 </tr>

<?php  }?>

</table>
</body>
</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
1

This will display any multidimensional array in an more readable format than print_r... Could be upgraded with different colors to contiguous cell to scroll rapidly through array... the space where you do not see an array,s name (key) or value will tell you the key/value if you hoover it... not pleasant visually but effective.

function show_array_as_table($array,$key_color='blue',$value_color="black",$fontfamily="arial",$fontsize="12pt") {
echo "<table style='color:{$color}; font-family:{$fontfamily}; font-size:{$fontsize}'>";
    foreach($array as $key => $value) {
    echo "<tr>";
        // key cell
    echo "<td title=\"{$key}\" style='width:150pt; height:25pt; text-align:right; vertical-align:top; background-color:cccccc; color:{$key_color}'><b>{$key}</b></td>";
        // value cell (will contain a table if the value is an array)
    echo "<td style='width:300pt; height:25pt; text-align:justify; vertical-align:top; color:{$value_color}'>";
        if (is_array($value)) {
        show_array_as_table($value,$key_color,$color,$fontfamily,$fontsize);
        } else {
        echo "<i>{$value}</i>";
        }
    echo "</td>";
    echo "</tr>";
    }
echo "</table>";
}
Phrank
  • 21
  • 4
0

This will also work:

echo "<table>";
foreach ($result as $key){
echo "
<tr>
<td>'".$key['id']."'</td>
<td>'".$key['first_name']."'</td>
<td>'".$key['last_name']."'</td>
</tr></table>
";
}
sam
  • 1
  • 5
0

In addition to @Phrank, it was more useful for me when I did it this way

function  show_array_as_table($array,$key_color='blue',$value_color="black",$fontfamily="arial",$fontsize="12pt") {

    foreach($array as $key => $value) {
        if (is_array($value)) {
    echo "<tr>";
    echo "<td title=\"{$key}\" style='width:150pt; height:25pt; text-align:right; vertical-align:top; background-color:cccccc; color:{$key_color}'><b>{$key}</b></td>";
        show_array_as_table($value,$key_color,$value_color,$fontfamily,$fontsize);
    echo "</tr>";
        } else {
    echo "<td style='width:300pt; height:25pt; text-align:justify; vertical-align:top; color:{$value_color}'>";
        echo "<i>{$value}</i>";
    echo "</td>";
        }
    }
}


echo "<table class='table'>";
echo show_array_as_table($reader);
echo "</table>";
-1
function array_to_table($array, $th_color = '#333', $td_color = "black", $font_family = "arial", $font_size = "12px"){
$array = json_decode(json_encode($array), true);
$tr = '';
$th = '<th style="border: 1px solid #eee;padding: 11px 21px; text-align:center; vertical-align:middle; background-color:#f7f7f7; color:' . $th_color . ';font-family:' . $font_family . '; font-size:14px">#</th>';
$isFetchedHeaders = false;
$i = 0;
foreach ($array as $row) {
    $td = '';
    $td .= '<td style="padding: 7px 11px; border: 1px solid #eee;text-align:center; vertical-align:middle; color:' . $td_color . ';font-family:' . $font_family . '; font-size:' . $font_size . '">' . ++$i . '</td>';
    foreach ($row as $column_key => $column) {
        if (!$isFetchedHeaders) {
            $th .= '<th style="border: 1px solid #eee;padding: 11px 21px; text-align:center; vertical-align:middle; background-color:#f7f7f7; color:' . $th_color . ';font-family:' . $font_family . '; font-size:14px">' . $column_key . '</th>';
        }
        $td .= '<td style="padding: 7px 11px; border: 1px solid #eee;text-align:center; vertical-align:middle; color:' . $td_color . ';font-family:' . $font_family . '; font-size:' . $font_size . '">' . $column . '</td>';
    }
    if (!$isFetchedHeaders) {
        $tr .= '<tr>' . $th . '</tr>';
    }
    $isFetchedHeaders = true;
    $tr .= '<tr>' . $td . '</tr>';
}
$table = '<table border="0" style="border-spacing: 0;">' . $tr . '</table>';
return $table;}
  • 1
    This answer is missing its educational explanation. In what why is this beneficial compared to other answers? How are you calling `array_to_table()`. Why should every row of data execute a check if `!$isFetchedHeaders`? Why is `$isFetcheHeaders` declared as `true` on each iteration? It only needs to be declared once. I feel there is too much code duplication here and the styling should be pulled out of the html markup. – mickmackusa Jun 01 '23 at 23:12
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 02 '23 at 01:03
  • 1
    Why did you edit the snippet but ignore the commented advice to improve your answer? – mickmackusa Jun 02 '23 at 05:41
  • Also, please don't put close braces on the same line as code. Saving a line isn't worth the sacrifice to readability. – General Grievance Jun 06 '23 at 16:04