【问题标题】:render HTML table from multidimensional array从多维数组呈现 HTML 表
【发布时间】:2017-01-13 04:47:53
【问题描述】:

我需要从多维数组中提取数据

       array(2) {
          ["label"]=>
          string(6) "label1"
          ["children"]=>
          array(3) {
            [1]=>
            array(1) {
              ["label"]=>
              string(6) "label2"
            }
            [2]=>
            array(1) {
              ["label"]=>
              string(6) "label3"
            }
           [3]=>
           array(2) {
             ["label"]=>
             string(6) "label4"
             ["children"]=>
             array(2) {
               [1]=>
               array(1) {
                 ["label"]=>
                 string(6) "label5"
               }
               [2]=>
               array(1) {
                 ["label"]=>
                 string(6) "label6"
               }
            }
          }
        }
      }

放入具有以下结构的表中:

	<table border="1">
   			<tr>
   				<td colspan="4">label1</td>
   			</tr>
   			<tr>
   				<td colspan="1">label2</td>
   				<td colspan="1">label3</td>
   				<td colspan="2">label4</td>
   			</tr>
   			<tr>
   				<td></td>
   				<td></td>
   				<td colspan="1">label5</td>
   				<td colspan="1">label6</td>
   			</tr>
   		</table>

数组的深度和结构是动态的,但基本规则保持不变。

关于我如何实现这一点的任何想法?谢谢!

【问题讨论】:

    标签: php html arrays


    【解决方案1】:

    将多维数组转换为单维数组,然后循环遍历单维,创建你需要的html字符串,即:

    转换数组: 见Convert multidimensional array into single array

    循环遍历 php 脚本中的单个数组并将字符串回显到浏览器:

    <?php
      function createHtml($singleArray){
        $html = '<table border="1">';
        foreach($singleArray as $label){
          $colspan = 1;
          //If then statement that sets $colspan based on label
    
          $html .= '<tr>';
          $html .= '<td colspan="'.$colspan.'">'.$label.'</td>';
          $html .= '</tr>';
        }
        $html .= '</table>';
        echo $html;
      }
    
    ?>
    

    【讨论】:

    • 不幸的是,您的解决方案每行只输出一个标签 (
      label1
      数组
      )。我需要每行有任意数量的标签(
      s),每个标签的“colspan”等于数组中的子节点数。
    猜你喜欢
    • 2014-01-11
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多