在PHP中更改数组的顺序

时间:2011-12-26 06:30:58

标签: php arrays

所以,我正在使用CMS,导航是根据“pages”目录中的页面动态生成的。然后我使用scandir()来构建页面数组和循环来构建导航。问题是,我希望能够通过用户定义的#更改导航中页面的顺序。

IE:“主页 - 联系我们 - 关于我们”可以更改为“主页 - 关于我们 - 联系我们”,具体取决于用户是否将“关于我们”页面的“权重”设置为较低的值。

<?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,所以我不擅长“最佳实践”或者做某些事情的正确方法。我为凌乱的代码道歉。

3 个答案:

答案 0 :(得分:1)

如果您正在使用CMS,那么我认为最好有一个用于生成静态页面的部分,其中包含为每个页面添加权重的选项,将其保存在数据库中,并根据分配给它的权重查询对其进行排序的页面。 根据您目前的情况,由于您使用的是scandir,因此只能按字母顺序排序:

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

参考:Sorting Scandir listing

答案 1 :(得分:0)

你可以在这里使用php中定义的“经典”排序排序函数列表http://php.net/manual/en/array.sorting.php但是如果你需要用户定义的排序,你可以检查这个函数uksort()uasort(),{{ 1}}取决于您对键或值进行排序所需的内容。

答案 2 :(得分: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>";

但是如果你要存储权重/索引,那么最好还是将当前页面存储在数据库中