dqkf36241 2008-11-05 15:11
浏览 28
已采纳

循环是构建表的最佳方法吗?

I have to build an HTML table that shows data for users versus pages visited. It seems klunky to use for and/or foreach loops, but I can't think of anything better. I'm using PHP, but I would assume that this is language agnostic.

  • 写回答

8条回答 默认 最新

  • dth20986 2008-11-05 15:21
    关注

    Avoiding loops is probably not possible, if not in implementation, then it will still happen at machine level.

    However, if you want to try stay 'pure' without nasty code, you can at least do:

    $tableformat = '<table><thead>%s</thead><tbody>%s</tbody></table>';
    $rowformat   = '<tr>%s</tr>'; 
    $cellformat  = '<td>%s</td>'; 
    
    $hdata = '';
    foreach( $data[0] as $cellname => $cellvalue )
    {
       $hdata  .= sprintf( $cellformat, $cellname ); 
    }
    $hdata = sprintf( $rowformat, $hdata ); 
    $rdata = "";
    foreach( $data as $rownum => $rowvalue ) 
    { 
       $row = "";
       foreach( $rowvalue as $colname => $colvalue ) 
       {
           $row .= sprintf( $cellformat, $colvalue );  
       }
       $rdata .= sprintf($rowformat,$row); 
    }
    return sprintf( $tableformat, $hdata, $rdata ); 
    

    At least that way it might be somewhat maintainable. and you don't have much worry about incomplete strings.

    You could also subsitutue some of that code with

       $hdata = "<tr><td>" . implode( "</td><td>", array_keys( $data[0] )) . "</td></tr>";
       $rdata .= "<tr><td>" . implode( "</td><td>", $rowvalue ) . "</td></tr>"; 
    

    Which while being rather concise, will possibly get you in a bit of hot water eventually and it will need recoding. ( and implode internally runs a loop, so its a lose-lose ).

    If you don't mind the over head of extra function calls ( and still running loops ) this could make for more concise code without too many negatives:

     $tableformat = '<table><thead>%s</thead><tbody>%s</tbody></table>';
     $rowformat   = '<tr>%s</tr>'; 
     $cellformat  = '<td>%s</td>'; 
    
    function tr( $cells )
    {  
       $o = "";
       foreach( $cells as $i => $v )
       {  
          $o .= sprintf( $cellformat, $v ); 
       }
       return sprintf( $rowformat, $o );  
    }
    
    
    return sprintf( $tableformat, 
                   tr( array_keys($data[0])), 
                   implode("", array_map( 'tr', $data )) ); 
    

    But beware, thats hard to read, and you keep that up one day you'll wake up with lisp.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办