I have a SQLite DB with a table called "library" containing 3 fields (12php sMb)
Id (unique identifier) // libraryName, containing a string // parentLibId, containing the ID of the parent Library.
If the library is in the "root", parentLibId is Null (empty)
I need an array that will return a tree with parents and child starting from t开发者_运维问答he root.
Anyone know how to do that without too many code?
$dbh = new PDO('sqlite:my.sqlite') or die("Error 0xDB0001");
$sth = $dbh->prepare("SELECT * FROM library");
$sth->execute();
$result = $sth->fetchAll();
I have a time processing page limit given by my friend as a little competition and this part I cannot figure it out, I used a code but it's so long, I feel stupid XD
Any help is welcomed, if I'm unclear, just say it and I'll give more details.
Thank you very much your help is appreciated!!
Have a good evening all!
this function is not tested. This is main idea.
getTree();
function getTree($child = null)
{
$dbh = new PDO('sqlite:my.sqlite') or die("Error 0xDB0001");
//It's just example. Security and best practice is your problem :p
if ($child)
$where = 'parentLibId = ' . $child;
else
$where = 'parentLibId IS NULL ';
$sth = $dbh->prepare("SELECT * FROM library" . $where);
$sth->execute();
if ($child)
{
$result = $sth->fetchAll()
$return = $result;
}else{ //get parents
while ($result = $sth->fetch())
{
//one by one
$return[] = array( 'parent' => $result, //parent info
'childs' => getTree($result['id']) //childs
);
}
}
return $return;
}
精彩评论