Skip to content

Instantly share code, notes, and snippets.

@olimortimer
Last active March 17, 2019 08:04
Show Gist options
  • Save olimortimer/4761541 to your computer and use it in GitHub Desktop.
Save olimortimer/4761541 to your computer and use it in GitHub Desktop.
PHP: Convert 'Adjacency List Model' database to a 'Nested Set Model' database
<?php
rebuild_tree(1, 1);
function rebuild_tree($parent_id, $left) {
// The right value of this node is the left value + 1
$right = $left+1;
// Get all children of this node
$this->db->select('id');
$this->db->from('geo');
$this->db->where('parent_id', $parent_id);
$result = $this->db->get();
foreach ($result->result() as $row) {
$right = $this->rebuild_tree($row->id, $right);
}
// We've got the left value, and now that we've processed
// the children of this node we also know the right value
$this->db->where('id', $parent_id);
$this->db->update('geo', array('lft' => $left, 'rgt' => $right));
// Return the right value of this node + 1
return $right+1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment