PHP - change/adding 数值到数组键值使用提交按钮

PHP - change/adding numerical value to array key value using submit button

我正在使用数组来限制 glob() 的结果,就像分页一样

$show = array(5,10,15,20);

$directories = glob(__DIR__.'/*', GLOB_ONLYDIR);
$directories = array_slice($directories, 0, $show[0]); // shows first 5 folders

如何使用按钮将值 1 添加到 $show[0]?

if(isset($_POST['submit'])){
  
  echo 'click submit to show 10 items, click again to show 15 items and so on';
  
};

您需要以某种方式记录页面的当前状态。您可以使用隐藏变量来执行此操作,但是我建议为此函数切换到 $_GET,或者仅使用查询字符串(正如我在此处所做的那样)。这样就可以直接在浏览器中转到正确的分页了URL吧。

PHP代码:

$show = array(5,10,15,20);
$current_page = 1; // this could also be 0 but setting it to 1 makes 'sense' to humans

if(isset($_GET['page']) && (int)$_GET['page'] > 0) {
    $current_page = $_GET['page']; // first set what the current page is

    if(isset($_POST['submit'])) {
        // since we know the submit button increments the page count only one direction, we can use this and simply...  Increment the current page :)
        $current_page++;
    }
} 

$directories = glob(__DIR__.'/*', GLOB_ONLYDIR);
$directories = array_slice($directories, 0, ($show[$current_page] - 1)); // shows first 5 folders ---- the "- 1" here is because we set $current_page to 1 above instead of 0.

然后你可以对 HTML 表单做这样的事情(使用我提到的查询字符串方法)

<form method="POST" action="?page=<?php echo $current_page; ?>">
    <input type="submit" name="submit" value="Submit!">
</form>