PHP display associative array in HTML table

冷暖自知 提交于 2019-12-06 05:44:27

Why not just modify the loop you already use to display the data?

echo "<table>";
foreach($req_data as $key=>$row) {
    echo "<tr>";
    foreach($row as $key2=>$row2){
        echo "<td>" . $row2 . "</td>";
    }
    echo "</tr>";
}
echo "</table>";
$toOutput = '<table>';
$showHeader = true;
$memberData = $reportObj->getMemberData();
while($row = mysql_fetch_assoc($memberData))
{
    $toOutput .= '<tr>';

    //Outputs a header if nessicary
    if($showHeader)
    {
        $keys = array_keys($row);
        for($i=0;$i<count($keys);$i++)
        {
            $toOutput .= '<td>' . $keys[$i] . '</td>';
        }
        $toOutput .= '</tr><tr>';
        $showHeader = false;
    }

    //Outputs the row
    $values = array_values($row);
    for($i=0;$i<count($values);$i++)
    {
        $toOutput .= '<td>' . $values[$i] . '</td>';
    }

    $toOutput .= '</tr>';
}
$toOutput .= '</table>';

echo 'Test page';
echo $toOutput;

Sorry for the necro, but I was actually looking to see if there was a build-in function for this as I was writing this.

yoyoyoyooyy
echo "<table border=\"5\" cellpadding=\"10\">";
for ($r=0; $r < count($row2); $r++) {
    echo "<tr>";
    for ($c=0; $c<$cols; $c++) { ?>
        <td> <?php $input[$r+$c] ?> </td>
    <?php }

    echo "</tr>";
    $r += $c;
}
echo "</table>";?>

Try something like this

echo "<table>";
for($r=0;$r<count($row2);$r++){
echo "<tr>";
for($c=0;$c<$cols;$c++){
echo "<td>".[VARIABLE YOU WANT TO PRINT]."</td>";
}
echo "</tr>";
}
echo "</table>";
you can try the following:

echo "The associative array<br>";
$computer=array("brand"=>"hp", "price"=>"800", "cpu"=>"core i7");
$keys=array_keys($computer);
echo "<table><tr>";
foreach($keys as $row){
    echo "<th style=\"border: solid 2px green\">".$row."</th>";
}echo "</tr><tr>";
foreach($computer as $col){
    echo "<td style=\"border: solid 2px blue\">".$col."</td>";
}echo "</tr></table>";
Александър Асенов
     function DumpTable($array_assoc) {
        if (is_array($array_assoc)) {
            echo '<table class="table">';
            echo '<thead>';
            echo '<tr>';
            list($table_title) = $array_assoc;
            foreach ($table_title as $key => &$value):
                echo '<th>' . $key . '</th>';
            endforeach;
            echo '</tr>';
            echo '</thead>';
            foreach ($array_assoc as &$master):
                echo '<tr>';
                foreach ($master as &$slave):
                    echo '<td>' . $slave . '</td>';
                endforeach;
                echo '</tr>';
            endforeach;
            echo '</table>';
            return;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!