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 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决