Skip to content

Instantly share code, notes, and snippets.

@sbreker
Created January 23, 2019 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbreker/abb17641a1f50045056ee77a8041dd97 to your computer and use it in GitHub Desktop.
Save sbreker/abb17641a1f50045056ee77a8041dd97 to your computer and use it in GitHub Desktop.
A different way to get ancestors.
<?php
$sql = "SELECT slug.object_id from slug where slug.slug = ";
$sql .= "'transfer-of-the-head-dress-ceremony-5';";
$sql = "SELECT id from information_object";
$rows = QubitPdo::fetchAll($sql);
$counter=0;
print(date('Y-m-d H:i:s'));
foreach($rows as $row)
{
$parentArray = array();
$parentArray[] = $row->id;
$start = microtime(true);
print(json_encode(getAncestors($parentArray)));
$time_elapsed_secs = microtime(true) - $start;
print(" " . $time_elapsed_secs . "\n");
$counter += 1;
}
print($counter."\n");
print(date('Y-m-d H:i:s'));
function getAncestors(&$ancestorArray, $tableName = 'information_object', $root_id = 1, $currentDepth = 0, $maxDepth = 50)
{
if (end($ancestorArray) == $root_id)
{
return $ancestorArray;
}
// Use SQL to get parent_id of last element of array
$sql = "SELECT t.id, t.parent_id";
$sql .= " FROM " . $tableName . " t";
$sql .= ' WHERE t.id=:id;';
$params = array(':id' => end($ancestorArray));
$row = QubitPdo::fetchOne($sql, $params);
// Add it to last element of array
$ancestorArray[] = $row->parent_id;
//print("ancestorArray: " . end($ancestorArray)."\n");
//print("t.parent_id: " . t.parent_id . "\n");
//print("root_id: " . $root_id."\n");
if ($row->parent_id == $root_id)
{
return $ancestorArray;
}
// Is currentDepth >= maxDepth? If so, trigger exception. Display last 20 elements of array. should never be circular parentage.
if ($currentDepth >= $maxDepth)
{
die("circular looping: ".json_encode($ancestorArray));
}
// If not, call self passing array in and currentDepth, and maxDepth
return getAncestors($ancestorArray, $tableName, $root_id, $currentDepth+1, $maxDepth);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment