繁体   English   中英

PHP - 使用提交按钮将数值更改/添加到数组键值

[英]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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM