private function buildMaps() { $list = $this->loadStubPages(); foreach ($list as &$page) { //restructure any child pages in the index, to the top level if (array_key_exists('childPages', $page)) { foreach ($page['childPages'] as $childPage) { $childPage['_parentPageCode'] = $page['code']; array_push($list, $childPage); } unset($page['childPages']); } //default some basic properties $page = array_replace(['code' => null, 'title' => null, 'slug' => null, 'module' => null, '_parentPageCode' => null], $page); } unset($page); //generate the lookup and tree $lookup = StructUtils::delegate($list, 'code'); $tree = StructUtils::tree($list, 'code', '_parentPageCode', 'childPages', 'parentPage'); foreach ($lookup as &$page) { unset($page['_parentPageCode']); //generate url $url = ''; $tempPage = $page; do { if ($tempPage['slug']) { $url = $tempPage['slug'] . '/' . $url; } } while (($tempPage = $tempPage['parentPage']) != null); $page['url'] = '/' . $url; //normalize item $page = $this->normalizeStubPage($page); } unset($page); $this->pagesLookup =& $lookup; $this->pagesTree =& $tree; }
/** * Creates a tree structure from a 2D, self-referencing source. * @param array $aArray Reference to a 2D array. * @param string $aPrimaryKey Key of 2nd level element whose value is its identifier. * @param string $aForeignKey Key of 2nd level element whose value is the identifier of its parent. * @param string $aChildrenKey Key of new element to be created, which stores an array of child elements. * @param string $aParentKey Key of new element to be created, which stores a reference to the parent element. * @throws Exception if a reference to a non-existent element is encountered. * @return array Nested structure of lookups. */ public static function tree(&$aArray, $aPrimaryKey, $aForeignKey, $aChildrenKey, $aParentKey) { $arr = array(); $lookup = StructUtils::delegate($aArray, $aPrimaryKey); //init each child array to empty foreach ($lookup as &$v) { $v[$aChildrenKey] = array(); } unset($v); foreach ($lookup as &$v) { if ($v[$aForeignKey] != null && !array_key_exists($v[$aForeignKey], $lookup)) { throw new Exception("Reference to non-existent element with identifier '" . $v[$aForeignKey] . "'."); } //if the current item references a parent if ($v[$aForeignKey] != null) { //set the parent key to a reference to the parent $v[$aParentKey] =& $lookup[$v[$aForeignKey]]; //add the current item to its parent's list of children $lookup[$v[$aForeignKey]][$aChildrenKey][$v[$aPrimaryKey]] =& $v; } else { //set the parent key to null $v[$aParentKey] = null; //add the current item to the top level $arr[$v[$aPrimaryKey]] =& $v; } } return $arr; }