Banco de Dados em árvore
Oi,
Achei na internet um script bem legal que pega valores de um banco de dados* e monta uma tabela no estilo árvore, como no Windows Explorer.
*O banco de dados é organizado assim: tem as colunas id, nome e pid... (pid indica qual o id-pai) (no script tem tb a coluna tipo, mas não tem nada a ver com a oganizacao da arvore)...
O script:
PHP
[*]<?
[*]
[*]mysql_connect('localhost', 'root', '') or die(mysql_error());
[*]mysql_select_db('ibiracu') or die(mysql_error());
[*]
[*]function get_tree() {
[*] global $current_level;
[*]
[*] $result = mysql_query('SELECT id, nome, pid, tipo
[*] FROM mapa-paginas
[*] ORDER BY nome') or die(mysql_error());
[*]
[*] while ($row = mysql_fetch_array($result)) {
[*] // create an array containing _all_ of the cateogries
[*] $temp_tree[] = array(
[*] 'id' => $row['id'],
[*] 'nome' => $row['nome'],
[*] 'pid' => $row['pid'],
[*] 'tipo' => $row['tipo']
[*] );
[*] }
[*] $temp_tree2 = $temp_tree;
[*]
[*] foreach ($temp_tree as $key => $value) {
[*] if (!$value['pid']) {
[*] // all right, it's a root category
[*] $current_level = 0;
[*]
[*] $new_tree[] = array(
[*] 'id' => $value['id'],
[*] 'nome' => $value['nome'],
[*] 'pid' => $value['pid'],
[*] 'tipo' => $value['tipo'],
[*] 'level' => $current_level
[*] );
[*]
[*] if ($branch = get_leafs($temp_tree, $value['id'])) {
[*] // merge the new array with the old array
[*] $new_tree = array_merge($new_tree, $branch);
[*] }
[*] }
[*] }
[*]
[*] return isset($new_tree) ? $new_tree : false;
[*]}
[*]
[*]function get_leafs($temp_tree, $id) {
[*] global $current_level;
[*]
[*] $current_level++;
[*]
[*] foreach ($temp_tree as $key => $value) {
[*] if ($value['pid'] == $id) {
[*] // all right, the parent id is a match
[*] $new_tree[] = array(
[*] 'id' => $value['id'],
[*] 'nome' => $value['nome'],
[*] 'pid' => $value['pid'],
[*] 'tipo' => $value['tipo'],
[*] 'level' => $current_level
[*] );
[*]
[*] if ($branch = get_leafs($temp_tree, $value['id'])) {
[*] // merge the new array with the old array
[*] $new_tree = array_merge($new_tree, $branch);
[*] }
[*]
[*] $current_level--;
[*] }
[*] }
[*]
[*] return isset($new_tree) ? $new_tree : false;
[*]}
[*]
[*]?>
Como chamar o script:
PHP
[*] <?
[*]foreach (get_tree() as $value) {
[*] echo str_repeat("--", $value['level'])." ".$value['nome']."<br />\n";
[*]}
[*]?>
O banco de dados em árvore funciona certo... acontece que eu to precisando modifica-lo e fazer, com que, por exemplo, só seja mostrado os filhos do id 5 (e todos os filhos dos filhos de 5 e por aí).
Alguém tem alguma idéia?
Discussão (11)
Carregando comentários...