stichpunkte: datenstrukturen und rekursive algorithmen.
ich versuche gar nicht genau zu verstehen warum dein programm nicht läuft - dazu ist der code zu konfus ($ausgabe0, $ausgabe[1], $ausgabe2, $ausgabe[3] ... ? mal ein string, mal ein array). weiterhin 2x das gleiche sql-query "SELECT * FROM menu" ? da steckt massiv der wurm drin.
also: das sql 1x ausführen, und aus dem ergebnis den menübaum aufbauen. dann den baum traversieren und gewünschten output erzeugen.
weil ich grade keine DB zur hand habe, das menu als statisches array $data.
wichtig ist: die hauptkategorien müssen 0 als parent_id haben (statt "") => "update menu set parent_id=0 where parent_id="" or parent_id is null)"
und damit korrekt einsortiert werden kann muss bei deinem sql noch ein order by parent_id erfolgen! weiterhin möchte dein kumpel bestimmt noch eine sortierung (sort int default 0) als zusätliche spalte bei menu hinterlegen können.
dann sollte folgender code weiterhelfen:
PHP-Code:
$data[] = array ('id' => 1, 'parent_id' => 0, 'name' => 'a', 'sort' => 1);
$data[] = array ('id' => 2, 'parent_id' => 0, 'name' => 'b', 'sort' => 2);
$data[] = array ('id' => 3, 'parent_id' => 1, 'name' => 'aa', 'sort' => 2);
$data[] = array ('id' => 4, 'parent_id' => 1, 'name' => 'ab', 'sort' => 1);
$data[] = array ('id' => 5, 'parent_id' => 2, 'name' => 'ba', 'sort' => 0);
$data[] = array ('id' => 6, 'parent_id' => 3, 'name' => 'aaa', 'sort' => 0);
$data[] = array ('id' => 7, 'parent_id' => 6, 'name' => 'aaaa', 'sort' => 0);
class CAT {
public $id;
public $parent;
public $name;
public $sort;
public $children = array();
public function __construct($id, $name, $sort) {
$this->id = $id;
$this->name = $name;
$this->sort = $sort;
}
public function insert (CAT $c, $parent_id) {
if ($parent_id == $this->id) {
$c->parent = $this;
$this->children[] = $c;
return true;
}
foreach ($this->children as $chld) {
if ($chld->insert ($c, $parent_id)) {
return true;
}
}
return false;
}
private $children_sorted = false;
private function sort() {
if (! $this->children_sorted) {
// falls output mehrfach aufgerufen wird nur einmal sortieren...
$this->children_sorted = true;
usort ($this->children, function ($a, $b) { return $a->sort - $b->sort;});
}
}
public function output ($indent = -1) {
if ($this->id != 0) {
echo str_repeat (' ' , $indent);
echo $this->name . "\n";
}
$this->sort();
foreach ($this->children as $chld) {
$chld->output ($indent+1);
}
}
public function output2 ($indent = 0) {
echo str_repeat (' ' , $indent);
$this->sort();
foreach ($this->children as $chld) {
echo $chld->name . ' ';
}
echo "\n";
foreach ($this->children as $chld) {
$chld->output2 ($indent+1);
}
}
}
$root = new CAT (0, 'root', 0);
foreach ($data as $c) {
$res = $root->insert (new CAT ($c['id'], $c['name'], $c['sort']), $c['parent_id']);
if (! $res) {
print_r ($c);
die ('kann c nicht einsortieren!');
}
}
$root->output();
echo "\nout2:\n";
$root->output2();
Code:
# php x.php
a
ab
aa
aaa
aaaa
b
ba
out2:
a b
ab aa
aaa
aaaa
ba
#