PHP树结构到Html表

时间:2015-08-28 12:16:18

标签: php html-table

我有一个场景,我有这样的树结构数据:

    $tree = array(
    1 => array(
        4 => array(),
        5 => array()
    ),
    2 => array(
        6 => array(),
        7 => array(
            11 => array()
        ),
        8 => array(
            12 => array(
                14 => array(),
                15 => array()
            )
        ),
    ),
    3 => array(
        9 => array(),
        10 => array(
            13 => array()
        )
    )
);

如何使用PHP递归函数创建一个html表:

1           |       2           |       3       |
4       5   |   6   7   |   8   |   9       10  |
            |       |11 |   12  |       |   13  |
                        |14 |15 |

我正在使用以下PHP代码:

function tree(array $data, &$tree = array(), $level = 0) {
    // init
    if (!isset($tree[$level])) $tree[$level] = array(count($array));

    foreach ($data as $key => $value) {

        // if value is an array, push the key and recurse through the array
        if (is_array($value)) {
            $tree[$level][] = $key;
            tree($value, $tree, $level+1);
        }
        // otherwise, push the value
        else {
           $tree[$level][] = $value;
        }
    }
}

function make_table($array)
{
    $output = '';
    foreach($array as $item => $tr)
    {
        $c = 100/count($tr);
        $output .= "<tr>";

        foreach($tr as $th => $val)
        {           
            $output .= "<th style='width:" . $c . "%'>" . $val . "</th>";
        }

        $output .= "</tr>";     
    }

    return $output;
}

但是上面的代码不像第一列的第三行那样处理空白区域。

1 | 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 |
14 | 15 |

1 个答案:

答案 0 :(得分:0)

你需要一些方法来跟踪colspans和表格中每个单元格的位置,然后用空单元格填充空白。

我今天写了这个,它似乎适用于你的例子:

$flipped = array_reduce(array_keys($arr), function ($carry, $item) use ($arr) {   
    $carry[$arr[$item]][] = $item;
    return $carry;
}, array());