【问题标题】:PHP - change/adding numerical value to array key value using submit buttonPHP - 使用提交按钮将数值更改/添加到数组键值
【发布时间】:2021-12-05 08:54:52
【问题描述】:

我正在使用数组来限制 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';
  
};

【问题讨论】:

    标签: php arrays arraylist submit array-key


    【解决方案1】:

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

    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>
    

    【讨论】:

    • 非常感谢。该代码完美运行,但我想将数组键限制为 4。当我超过数组值的数量时,它返回“未定义的数组键 5”。
    • $current_page++;行替换为if($current_page &lt; count($show)) { $current_page++; }
    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2012-10-08
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    相关资源
    最近更新 更多