Php从动态td tr创建表

我试图用动态行单元格从动态数组创建一个表。


当在数组中找到行时,它将<tr>首先添加标签,直到row在数组中找到下一个。我想当找到的行tr标记将从td内部标记开始,直到在数组中找到下一行然后再次相同的tr标记将开始,直到在数组中找到下一行。


这是一个数组的例子


$cars = array (

      array(

          'table_body_element'=>'row',

          'cell_text'=>'',

      ),

      array(

          'table_body_element'=>'cell',

          'cell_text'=>'Column 1',

      ),

      array(

          'table_body_element'=>'cell',

          'cell_text'=>'Column 2',

      ),

      array(

          'table_body_element'=>'cell',

          'cell_text'=>'Column 3',

      ),

      array(

          'table_body_element'=>'row',

          'cell_text'=>'',

      ),

      array(

          'table_body_element'=>'cell',

          'cell_text'=>'Column 11',

      ),

      array(

          'table_body_element'=>'cell',

          'cell_text'=>'Column 22',

      ),

      array(

          'table_body_element'=>'row',

          'cell_text'=>'',

      ),

    );

我试图检查它是否为行标记并在其上添加 tr 标记。


这是我的 foreach 循环。


echo '<table><thead><tr>';

foreach ($cars as $item){

    echo '<td>'.$item[ 'cell_text' ].'</td>';

    if( $item[ 'table_body_element' ] == 'row' ){

        echo '</tr><tr>';

    }

}

echo '</tr></tbody></table>';

输出

http://img.mukewang.com/61a9d87700018cb508190627.jpg

现在的输出显示如下。使用没有 td 内容的快速空 tr div 和最后一个没有内容的 tr div 打印。我想删除这个唯一的内容 tr 标签,并且 td 需要在结果中打印。


呼如林
浏览 229回答 2
2回答

开心每一天1111

问题是你总是先放出单元格文本,即使是rows,当你得到一个新行时,你总是打开下一行......echo '</tr><tr>';至少你关闭它,但很难(不维护各种标志)决定何时输出开始标签。另类,这构建了每一行,然后使用implode()了该$rows阵列添加<tr></tr>标签一轮他们...echo '<table><thead>';$rows = [];$row = '';foreach ( $cars as $car )&nbsp; &nbsp;{&nbsp; &nbsp; if ( $car['table_body_element'] == 'row' ) {&nbsp; &nbsp; &nbsp; &nbsp; if ( !empty($row) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $rows [] = $row;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $row = '';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $row .= '<td>'.$car[ 'cell_text' ].'</td>';&nbsp; &nbsp; }}echo '<tr>'.implode( '</tr><tr>', $rows ).'</tr>';echo '</tbody></table>';

慕娘9325324

最好将 foreach 放在表格中,在我看来,在 foreach 的末尾放置并不好。尝试这个:echo '<table><tbody>';foreach ($cars as $item){&nbsp; &nbsp; echo '<tr><td>'.$item[ 'cell_text' ].'</td>';&nbsp; &nbsp; if( $item[ 'table_body_element' ] == 'row' ){&nbsp; &nbsp; &nbsp; &nbsp; echo '</tr>';&nbsp; &nbsp; }}echo '</tbody></table>';
打开App,查看更多内容
随时随地看视频慕课网APP