php从数组创建表

时间:2011-05-18 16:12:04

标签: php html arrays

Array ( [0] => stdClass Object ( 
                  [logtime] => 1305732210 
                  [useragent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0 
                  [remotehost] => 188-24-176-75.rdsnet.ro 
                  [page] => RSS.php 
                  [qs] => [action] => view page )

        [1] => stdClass Object ( 
                  [logtime] => 1305732216 
                  [useragent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0 
                  [remotehost] => 188-24-176-75.rdsnet.ro 
                  [page] => Pages.php 
                  [qs] => page=angajari 
                  [action] => view page ) 
)

如何将此数组显示为表

             **| crt |logtime | useragent  | remotehost | action |
             ---------------------------------------------------
array values |  1  |        |            |            |        |
             ---------------------------------------------------
array values |  2  |        |            |            |        |
             ---------------------------------------------------**

3 个答案:

答案 0 :(得分:2)

echo '<table><tr><th>....';
foreach($arr as $o){
  echo >>>EOTR
<tr>
  <td>{$o->logtime}</td>
  <td>{$o->useragent}</td>
  <td>{$o->remotehost}</td>
  <td>{$o->page}</td>
  <td>{$o->action}</td>
</tr>
EOTR;
}
echo '</table>';

答案 1 :(得分:2)

dnagirl的方法有效,但这里是“模板格式”,如果您需要这种方式(注意:如果您无法控制服务器和/或PHP,请将<?=替换为<?php echo short_tags已关闭):

<table><tr><th>
<?php foreach($arr as $o): ?>

<tr>
  <td><?= $o->logtime ?></td>
  <td><?= $o->useragent ?></td>
  <td><?= $o->remotehost ?></td>
  <td><?= $o->page ?></td>
  <td><?= $o->action ?></td>
</tr>
<?php endforeach; ?>
</table>

答案 2 :(得分:1)

编辑:对不起,我完全错过了那个数组中的对象。这个解决方案是错误的。

这将是更通用的解决方案。

echo '<table><tr><td>crt</td>';
    foreach($arr[0] as $key => $val1){
      echo "<td>$key</td>";
    }
    echo '</tr>';
    foreach($arr as $key => $val){
      echo " <tr> <td>".($key+1)."</td>";
        foreach($val as $key => $val1){
          echo "<td>$val1</td>";
        }
      echo " </tr> ";
    }
    echo '</table>';