PHP如何通过提交按钮调整数组索引实现glob结果分页数量递增
实现方案
核心是用session跨请求保存当前的展示条数索引,解决HTTP无状态导致的变量每次请求重置的问题,同时做数组下标越界防护。
完整可运行代码
<?php // 开启session,用于持久化存储当前使用的展示条数索引 session_start(); $show = [5, 10, 15, 20]; // 首次访问默认索引为0,对应展示5条 $currentIndex = $_SESSION['show_index'] ?? 0; if (isset($_POST['submit'])) { // 索引自增,最大不超过数组最后一位的下标,避免越界报错 $currentIndex = min($currentIndex + 1, count($show) - 1); // 把更新后的索引存入session,下次请求生效 $_SESSION['show_index'] = $currentIndex; } // 按当前索引对应的条数截取目录列表 $directories = glob(__DIR__ . '/*', GLOB_ONLYDIR); $directories = array_slice($directories, 0, $show[$currentIndex]); // 示例:输出目录列表 foreach ($directories as $dir) { echo '<p>' . basename($dir) . '</p>'; } ?> <!-- 提交按钮表单 --> <form method="post"> <button type="submit" name="submit">点击展示更多目录</button> <p>当前共展示 <?php echo $show[$currentIndex]; ?> 条目录</p> </form>
可选拓展
如果需要展示到最大条数后,再次点击回到最小条数循环展示,把提交逻辑里的索引更新代码换成下面的即可:
$currentIndex = ($currentIndex + 1) % count($show);
内容的提问来源于stack exchange,提问作者FUNDIY
相关产品推荐
相关产品推荐

