I have a scenario where I have a tree structure data like this:
$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()
)
)
);
How to create a html table using PHP recursive function like this:
1 | 2 | 3 |
4 5 | 6 7 | 8 | 9 10 |
| |11 | 12 | | 13 |
|14 |15 |
I am using following PHP code:
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;
}
But the above code does not handle empty space like in third row of first column.
1 | 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 |
14 | 15 |