2011-12-26 105 views
0

因此,我正在開發CMS,導航是根據「頁面」目錄中的頁面動態生成的。然後,我使用scandir()構建頁面數組和循環來構建導航。問題是,我希望能夠通過用戶定義的#來改變導航頁面的順序。根據用戶是否將「關於我們」頁面的「重量」設置爲較低的值,IE:「主頁 - 聯繫我們 - 關於我們」可以更改爲「首頁 - 關於我們 - 聯繫我們」。在PHP中更改數組的順序

<?php 

$views_dir = $_SERVER['DOCUMENT_ROOT']."kloudcms/".VIEWS_LOCATION; 
$views = scandir($views_dir, 0); 
unset($views[0], $views[1]); 

echo "<ul>"; 
foreach ($views as $view) { 
    $page_name = substr($view, 0, count($view) - 5); 
    echo "<li>".ucwords($page_name)."</li>"; 

} 
echo "</ul>"; 


?> 

另外,我知道代碼是混亂的。我一直在學習PHP大約一個月,所以我不擅長「最佳實踐」或適當的方式去做某些事情。我爲這個混亂的代碼道歉。

回答

1

如果您使用CMS,那麼我認爲它能夠更好地對生成靜態頁面與選項,以增加重量的每一頁,保存在數據庫中,查詢頁面根據分配給它的權重排序它的部分。 根據你目前的情況,因爲你正在使用SCANDIR,你只能按字母順序排序:

 
scandir (string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]]) 

編號:Sorting Scandir listing

+0

噢噢噢,好吧。我不知道。我會嘗試這種方式,看看我得到了什麼。謝謝! – tetshi 2011-12-26 06:46:20

0

你可以在PHP中使用這裏定義的排序功能http://php.net/manual/en/array.sorting.php名單「經典」之類的但如果你需要某種定義的用戶,你可以檢查你需要的鍵或值進行排序一下這個功能uksort()uasort()uasort()依賴。

+0

謝謝,我現在就放棄一下,看看我想出了什麼。 – tetshi 2011-12-26 06:46:44

0
//get this from somewhere (a DB or file) - higher the index the later it will be listed 
$indexs = array(
    'Home'=>1, 
    'About Us'=>3, 
    'Contact Us'=>2 
); 
$output = array(); 
//count incase no index's defined 
$i = 0; 
foreach($views as $view){ 
    $output[$view] = isset($indexs[$view]) ? $indexs[$view] : $i++; 
} 
//sort array by index's assigned 
asort($output); 
//implode array and use the array key value (not the index value) to output 
echo "<ul><li>".implode('</li><li>', array_keys($output))."</li></ul>"; 

但是如果你存儲的權重/索引的,你也最好存儲當前頁面數據庫中的

+0

我想我會堅持數據庫的想法。我最近轉換爲準備好的語句和MySQLI,所以這樣做變得更容易。感謝代碼,很高興知道我能做到這一點。 – tetshi 2011-12-26 21:58:22