$sql = 'SELECT page_id, page_parent FROM pages ORDER BY page_parent';$stmt = $db->prepare($sql);$rawData = 数组();$stmt->execute();while ($row = $stmt->fetch()) {$parent = $row['page_parent'];$child = $row['page_id'];如果 (!array_key_exists($parent, $rawData)) {$rawData[$parent] = array();}$rawData[$parent][] = $child;}要进行转换,您需要类似于:$tree = new Tree();$tree->rebuild($rawData);因此,基本上您创建一个数组,其中包含由父索引索引的树中的所有节点,这些节点将以递归方式遍历以确定每个节点的正确左值和右值.顺便说一句,你可以用普通的 SQL 来完成(在你调整表/列名之后):http://bytes.com/topic/mysql/answers/638123-regenerate-nested-set-using-parent_id-structureI am having trouble trying to move sub nodes or parent nodes up or down... not that good at math.As example how would I move TEST up above PARENT and say move SUB down below SUB-SUB by playing with the page-left/page-right IDs? Code is not required just help with the SQL concept or math for it, would help me understand how to move it better... 解决方案 So basically you want to convert an adjacency list to a nested set? First update your adjacency list (ie. update the page_parent values to the correct values for your new tree), then run the conversion below.Using PHP (basic code, untested) :class Tree{ private $count = 0; private $data = array(); /** * Rebuild nested set * * @param $rawData array Raw tree data */ public function rebuild($rawData) { $this->data = $rawData; $this->count = 1; $this->traverse(0); } private function traverse($id) { $lft = $this->count; $this->count++; if (isset($this->data[$id])) { $kid = $this->data[$id]; if ($kid) { foreach ($kid as $c) { $this->traverse($c); } } } $rgt = $this->count; $this->count++; // TODO: Update left and right values to $lft & $rgt in your DB for page_id $id ... }}When you call this, $rawData should contain an array of ID's, indexed by parent-id, you could create it (based on your table structure) as follows ($db should contain an active PDO connection object): $sql = 'SELECT page_id, page_parent FROM pages ORDER BY page_parent'; $stmt = $db->prepare($sql); $rawData = array(); $stmt->execute(); while ($row = $stmt->fetch()) { $parent = $row['page_parent']; $child = $row['page_id']; if (!array_key_exists($parent, $rawData)) { $rawData[$parent] = array(); } $rawData[$parent][] = $child; }To do the conversion you would need something like :$tree = new Tree();$tree->rebuild($rawData);So basically you create an array that is containing all nodes in your tree indexed by parent which will be traversed in a recursive manner to determine the correct left and right values per node.BTW You could do it in plain SQL (after you adapt table/column names) :http://bytes.com/topic/mysql/answers/638123-regenerate-nested-set-using-parent_id-structure 这篇关于PHP 移动 mySQL 树节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
06-16 11:14