簡體   English   中英

PHP添加隨機數組不重復最近5

[英]php add random array not repeating most recent 5

我試圖重新編寫此代碼,以便它與將要由用戶定義的列一起使用。 因此,我的挑戰包括:a)需要從數組中選擇隨機起始項b)從原始數組中選擇下一個隨機顏色,該顏色與基於數字選擇的最新項目不相等:$ intNotesColumn + 1

我當時認為嵌套在另一個語句中的do-while語句適合此操作,但是不確定如何執行此操作。 到目前為止,這是我的代碼:

 $metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
 $metroUIcolorsLength = count($metroUIcolors);
 $intNotesColumn = 3; // This will be user-defined later
 // Now I query the SQL database to get my base-code
 if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
     . '<tr>'
     . '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>' 
     . '</tr>'
     . '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
    echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">" 
             . "<h2>" . $row["username"] . '</h2><br />'
             . "<p class='notes'>" .  $row["notes"] . "</p>"

             . "<p class='footnotes'>"
             . "<br />Last Reset:  " . $row["lastReset"]
             . '<br />Last Update:  ' . $row['lastUpdate'] 
             . '<br />SessionID:  ' . $row["sessionID"] 
             . "<br />Counter = " . $counterRank . "</td>". '</p>';

    if ($counterRank % $intNotesColumn == 0)
    {
      echo '</tr><tr>';
    }
    $counterRank++;
}
     echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}

然后,為什么不按順序選擇一種顏色呢? 您可以使用shuffle()以便每次都有不同的起始顏色。

<?php
$counterRank = 1;

// shuffle the array
shuffle($metroUIcolors); 

while($row = $result->fetch_assoc()) {
    $rand_color = $counterRank % $metroUIcolorsLength;
     echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";

     // everything else

   $counterRank++;
}

?>

如果您堅持按照您所說的方式進行操作,則可以創建一個數組$colorCount ,該數組的顏色代碼為鍵,計數為值。

<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);

while($row = $result->fetch_assoc()) {
    do {
        $rand_color =  $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
    } while ($colorCount[$rand_color] > 5);


    echo "<td bgcolor=" . $rand_color. ">";

     // everything else

   $counterRank++;
   $colorCount[$rand_color] += 1;
}

?>

暫無
暫無

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

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