繁体   English   中英

使用post数据的数组搜索获取数组中的下一个元素

[英]Array search with post data get next element in the array

每次我点击下一个按钮时,它都会在第一个已经在数组中搜索的元素中出现。 这是我的示例代码:

<?php

$letter = 'A';

if (isset($_POST["next"])) 
{
    if(isset($next))
    {
        unset($letter);
        $letter = $next;
    }

    $alphabet = array('A', 'B', 'C', 'D', 'E');

    $get = array_search($letter, $alphabet);

    $next = $alphabet[$get + 1];

    echo $next;
}

?>

<form name="alphabet" method="post"> 
<input type="submit"  name="next" value="next"/>
</form>

输出是:

B

我想要的输出是:

A-> B-> C-> D

每次单击下一个按钮时如何转到每个下一个元素&如果显示的最后一个元素我希望它转到数组中的第一个元素,就像它循环到第一个元素一样。 我不想使用$ _GET我想要$ _POST。 请帮我解决这个问题? 谢谢。

试试这个。 您需要将变量发布回脚本,以便在每次加载页面时,它可以知道之前的值是什么。

<?php
        $letter = 'A';

        if (isset($_POST["letter"]))
        {
            $letter = $_POST["letter"];

            $alphabet = array('A', 'B', 'C', 'D', 'E');

            $get = array_search($letter, $alphabet);

            if($get < (count($alphabet) - 1))
            {
                $get++;
            }
            else
            {
                $get = 0;
            }

            $letter = $alphabet[$get];

            echo $letter;
        }

        ?>

        <form name="alphabet" method="post">
            <input type="hidden"  name="letter" value="<?php echo $letter ?>" />
            <input type="submit"  value="next" />
        </form>

编辑 :已添加对索引变量$get的检查,如果它不在数组末尾,则仅增加,否则应重置。

试试这个。 我们将当前字母作为隐藏的后置变量传递。

<?php

$alphabet = array('A', 'B', 'C', 'D', 'E');
$next = 'A';   //for the first call of page.
if (isset($_POST["next"])) 
{

    $letter = $_POST['letter'];

    $get = array_search($letter, $alphabet);

    $next = $alphabet[($get + 1)%count($alphabet)];  //for loop over array

}

echo $next;
?>

<form name="alphabet" method="post"> 
<input type="hidden"  name="letter" value="<?php echo $next;?>"/>
<input type="submit"  name="next" value="next"/>
</form>

暂无
暂无

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

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