2013-07-12 40 views
0

我有一个数据库有一些问题,我希望每次页面是打开,不刷新以不同顺序显示它们。每次打开页面时都会打乱数组值,没有会话?

的洗牌,这是确定:

function shuffle_keys(&$array) { 
    $keys = array_keys($array); 

    shuffle($keys); 
    foreach($keys as $key) { 
     $new[$key] = $array[$key]; 
    } 

    $array = $new; 
} 

从数据库中随机播放与价值观的阵列进行打印:

shuffle_keys($array_questions); 
foreach($array_questions as $key => $val) { 
    $key_value = ++$key; 
    echo "<a href = '?id=$val'>".$key_value."</a> "; 
} 

刚才,当我刷新每次洗牌是不同的,我希望它这种方式只有当我第一次打开页面。

+2

你需要使用会话。 HTTP是一个无状态协议 – DevZer0

+2

在我看来,你的'shuffle_keys($ array)'和'shuffle($ array)'完全一样,只是更复杂。 – deceze

回答

1

如果你想为同一届同一个洗牌,(这是我的理解)

可以使用$_SESSION变量来存储您的阵列。

session_start(); 
if (isset($_SESSION['array_questions'])) 
    $array_questions=$_SESSION['array_questions']; 
else 
{ 
shuffle_keys($array_questions); 
foreach($array_questions as $key => $val) { 
    $key_value = ++$key; 
    echo "<a href = '?id=$val'>".$key_value."</a> "; 
} 
$_SESSION['array_questions']=$array_questions; 
} 
1

您无法自行检测页面刷新。也许考虑设置一个cookie并断言它是否在页面打开时存在?

0

您可以使用一个静态变量。只要创建一个类,如下:

class Base { 

    protected static $variable = 0; 
} 

class child extends Base { 

    function set() { 

     self::$variable = 1; // let say 1 = 'sorted' 
    } 

    function show() { 

    echo(self::$variable); 
    } 
} 

现在,当你进入你的网站,

创建一个对象,并设置变量,调用方法

$c1 = new Child(); 
if($c1->show() == 0) 
{ 
    // sort your array here and set the static flag to sorted(1) 

    $c1->set(); 
} 

希望这有助于...

+0

'static'不会在单独的页面加载中持续存在! – deceze

+0

糟糕!我不知道,那么我们可以使用$ GLOBALS [“foo”]作为案例吗? –

+0

不! http://stackoverflow.com/a/17611705/476 – deceze

相关问题