Skip to content

Instantly share code, notes, and snippets.

@phawk
Created January 4, 2012 09:49
Show Gist options
  • Save phawk/1559358 to your computer and use it in GitHub Desktop.
Save phawk/1559358 to your computer and use it in GitHub Desktop.
php recursive closure
public function save()
{
//
// Find the root ID of the category to make selecting much easier
//
// Get all categories
$all_categories = $this->all_categories();
$parent_id = $this->get_parent_id();
// A recursive closure to go up all the levels to root category and get its ID
// We need to pass this closure to itself by reference and pass the array of all categories by reference
$find_root_id = function ($parent_id) use (&$find_root_id, &$all_categories) {
$parent_category = $all_categories[$parent_id]; // Get the parent category from the ID
$id = $parent_category->get_id(); // Get the ID of the parent
$parent_id = $parent_category->get_parent_id(); // Get the parents parent ID
if ($parent_id == null)
{
// If parent ID is null we need to return its ID as it is the root category
return $id;
}
else
{
// If parents ID is not null, we call this function again recursively
return $find_root_id($parent_id);
}
};
// Set the root ID of the object to the one found by the closure
$this->set_root_id($find_root_id($parent_id));
parent::save();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment