Skip to content

Instantly share code, notes, and snippets.

@xat
Last active December 20, 2015 13:49
Show Gist options
  • Save xat/6141235 to your computer and use it in GitHub Desktop.
Save xat/6141235 to your computer and use it in GitHub Desktop.
<?php
function treeWalker($fnCallback, $strTable, $intStart=0, $orderBy='pid, sorting')
{
$arrItemsByPid = array();
$arrItems = \Database::getInstance()->execute('SELECT * FROM ' . $strTable . ' ORDER BY ' . $orderBy)->fetchAllAssoc();
$strResult = '';
foreach($arrItems as $arrItem)
{
$arrItemsByPid[$arrItem['pid']][] = $arrItem;
}
function iterate($pid, &$arrItemsByPid, &$fnCallback, &$strResult, $level=0)
{
for ($i=0, $len=count($arrItemsByPid[$pid]); $i<$len; $i++)
{
$arrItem = $arrItemsByPid[$pid][$i];
$varRes = $fnCallback($arrItem, $level, $i, $i===$len-1);
if (is_string($varRes))
{
$strResult .= $varRes;
}
if (isset($arrItemsByPid[$arrItem['id']]))
{
iterate($arrItem['id'], $arrItemsByPid, $fnCallback, $strResult, $level+1);
}
}
};
iterate($intStart, $arrItemsByPid, $fnCallback, $strResult, 0);
return $strResult;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment