0

My included file (include.php) is this:

<?php
$myarray=(a,b,c);
shuffle($myarray);
?>

My main php file is this:

include('include.php');

if isset($_POST['submit_button']){
      echo "Button was clicked";
      echo $myarray;
      }
else {
     echo "Not clicked."; 
     echo $myarray;
     }
?>

<form method='POST'><input type='submit' name='submit_button'></form>

Why are the elements of $myarray displayed in a different order after I clicked the button? Isn't it shuffled only once?

How can I prevent the shuffle from being executed more than one time? (so that I can display the elements of myarray in the same order, before and after the button was clicked)

4

2 回答 2

2

您的 PHP 文件会根据每个请求进行解释。正如您现在所拥有的那样,您的系统中没有内存,因此您的文件无法“记住”数组已经被洗牌。此外,如果您将数组洗牌一次,然后再次加载页面,并且设法洗牌,则数组将是(a,b,c),因为变量被初始化为(a,b,c)并且从不洗牌。

做你想做的事,如果我理解正确,你可以使用会话。

$myarray=(a,b,c);

if (!isset($_SESSION['shuffled'])) {
    shuffle($myarray);
    $_SESSION['shuffled'] = $myarray;
} else {
    $myarray = $_SESSION['shuffled'];
}
于 2012-04-04T03:36:14.840 回答
1

发生这种情况是因为每次加载页面时,都会包含该文件,这也会再次对数组进行洗牌。

尝试使用serialize()然后按您想要的顺序发布数组。检索它使用unserialize()

http://www.php.net/manual/en/function.serialize.php

于 2012-04-04T03:31:53.327 回答