Created
June 14, 2020 11:03
-
-
Save veeenu/5e5c15a2aba61534eb8d156d5a608434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$dati = [ | |
[ | |
'name' => 'Tizio', | |
'id' => 1, | |
'parent' => null | |
], | |
[ | |
'name' => 'Caio', | |
'id' => 2, | |
'parent' => 1 | |
], | |
[ | |
'name' => 'Sempronio', | |
'id' => 3, | |
'parent' => 1 | |
], | |
[ | |
'name' => 'Paolo', | |
'id' => 4, | |
'parent' => 2 | |
], | |
[ | |
'name' => 'Roberto', | |
'id' => 5, | |
'parent' => 2 | |
], | |
[ | |
'name' => 'Giuseppe', | |
'id' => 6, | |
'parent' => 3 | |
], | |
]; | |
class Nodo { | |
public $name; | |
public $id; | |
public $parent; | |
public $figli = []; | |
public function __construct($o) { | |
$this->name = $o['name']; | |
$this->id = $o['id']; | |
$this->parent = $o['parent']; | |
} | |
public function inserisci($nodo_padre) { | |
if ($nodo_padre->id == $this->parent) { | |
array_push($nodo_padre->figli, $this); | |
} else { | |
foreach ($nodo_padre->figli as $figlio) { | |
$this->inserisci($figlio); | |
} | |
} | |
} | |
public function to_li() { | |
$res = '<li>' . $this->name; | |
if (count($this->figli) > 0) { | |
$res .= '<ul>'; | |
foreach ($this->figli as $f) { | |
$res .= $f->to_li(); | |
} | |
$res .= '</ul>'; | |
} | |
return $res; | |
} | |
} | |
$radice = new Nodo($dati[0]); | |
foreach (array_slice($dati, 1) as $dato) { | |
$nodo = new Nodo($dato); | |
$nodo->inserisci($radice); | |
} | |
print('<pre>'); | |
print_r($radice); | |
print('</pre>'); | |
print('<ul>' . $radice->to_li() . '</ul>'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment