簡體   English   中英

PHP隨機文本一次

[英]PHP random text once

多年來,我一直在尋找解決問題的方法,但至今仍未找到答案,因此我決定創建一個stackoverflow帳戶來問自己一個問題。

這是我到目前為止創建的:

<? //Chooses a random number $num = Rand (1,2);
switch ($num){
case 1: $retrieved_data = "test"; break;
case 2: $retrieved_data = "test1"; break;
} ?> 

這是我希望文字出現的地方;

<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input name="<?php echo $retrieved_data; ?>" type="file" />
<input type="submit" value="Upload" /></form>

我的問題是我想在這些地方隨機顯示“ test1”和“ test”,但我希望它們每次都彼此不同。 因此,如果第一個輸入類型為“ test”,我希望第二個輸入類型為“ test1”,但我似乎無法正常工作

有誰知道我在做什么錯或者有代碼使之成為可能?

如果可能性有限,請將它們放入一個數組,將其洗牌並從中移入/彈出元素:

$retrieved_data = array('test', 'test1');
shuffle($retrieved_data);

$random1 = array_shift($retrieved_data);
$random2 = array_shift($retrieved_data);

步驟A-您正在選擇一個數字,是1還是2步驟B-您正在通過交換機的情況下運行該數字,這種情況下,僅接受它所接收的數字並為其分配一個值。 因此,如果您的數字為1,則切換條件以$ retrieved_data =“ test”結尾。 如果您的數字是2,則切換用例進入情況2,並分配$ retrieved_data =“ test 1”。 步驟C = $ retrieved_data被分配給您的表單(它將只有一個值“ test”或“ test1”。

為此使用array_rand()

$aName = array('test1', 'test2', 'whatever');

function getRandom(array &$aName)
{
    if (($key = array_rand($aName)) === NULL) {
        throw new Exception('No more randomness!');
    }

    $value = $aName[$key];
    unset($aName[$key]);
    return $value;
}

因此,當您需要數組中唯一的隨機項時,只需使用getRandom($aName)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM