嵌套的<span>
方法:
如果數據庫返回以下爲$results
:
id pid name description
1 0 Caninae
2 1 Canis
3 2 adustus Side-Striped Jackel
4 2 anthus African Golden Wolf
5 2 aureus Golden Jackel
您可以創建表上面的:
function print_table(){
$results = some_sql_function();
//$hierarchy contains an array of childern and an array of data
$hierarchy = create_hierarchy($results);
$data = $hierarchy['data'];
$index = $hierarchy['index'];
//Create the table header
$output = "<table>";
$header = "<tr><th>Name</th><th>Description</th></tr>";
$output .= $header;
$rows = create_rows($data, 0, $index, 0);
$output .= $rows . "</table>";
echo $output;
}
// Iterating function to nest the childern rows beneith the parents
function create_rows($data, $parent_id, $index, $level){
$rows = "";
if (isset($index[$parent_id])) {
foreach ($index[$parent_id] as $id) {
$cell1 = str_repeat('<span style="padding-left:20px">',$level) . $data[$id]["name"] . str_repeat('</span>',$level);
$cell2 =$data[$id]['description'];
$row = "<tr><td>$cell1</td><td>$cell2</td></tr>";
$rows .= $row;
$rows .= create_rows($data, $id, $index, $level + 1));
}
}
return $rows;
}
function create_hierarchy($results) {
//The data associated with each account
$data = array();
//A list of an account's children
$index[] = array();
foreach ($results as $row){
$id = $row->id;
$name = $row->name;
$parent_id = $row->pid;
$description = $row->description;
$data[$id] = array('name'=>$name, 'description'=>$description);
$index[$parent_id][] = $id;
}
$hierarchy = array('data'=>$data, 'index'=>$index);
return $hierarchy;
}
我修改了Drupal的代碼是純PHP,所以可能有一些微小的錯誤,但是這是我做的。
這感覺這應該是表格內的表格而不是單個表格。 –