1

我正在使用以下教程来学习如何在 PHP 中洗牌,但输出很难看。如何更改随机播放的输出以更符合我想以列表格式显示的投票?

我正在使用以下教程来学习如何做到这一点:

http://www.w3schools.com/php/func_array_shuffle.asp

<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

shuffle($my_array);
print_r($my_array);
?

但是输出很难看: Array ( [0] => Cat [1] => Dog [2] => Horse )

如何使随机播放数组看起来像这样漂亮?

<ul>
<li><input id="pollRadioButton1" name="pollAnswerID" type="radio" value="1" /> Answer1 for Poll1</li>
<li class="pollChart pollChart1">&nbsp;</li>
<li><input id="pollRadioButton2" name="pollAnswerID" type="radio" value="2" /> Answer2 for Poll1</li>
<li class="pollChart pollChart2">&nbsp;</li>
</ul>
4

2 回答 2

2
<?php

    $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");
    shuffle($my_array);

?>
<ul>
    <?php foreach ($my_array as $key => $element): ?>
        <li>
            Whatever you want to do with
            <?php echo htmlspecialchars($element) ?>
            (<?php echo htmlspecialchars($key) ?>).
        </li>
        <li class="pollChart pollChart1">&nbsp;</li>
    <?php endforeach ?>
</ul>
于 2012-11-19T11:23:31.747 回答
-1

print_r()只是为了调试而提到的。

要获得“干净”的输出,您必须指定应如何输出:

<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

shuffle($my_array);

foreach ($my_array as $key=>$val)
    echo sprintf('%s: %s<br>'."\n",$key,$val);
?>

在您的情况下,输出可能类似于:

echo sprintf('<li><input id="pollRadioButton[]" name="%1$s" '.
             'type="radio" value="%2$s" />%2$s</li>'."\n".
             '<li class="pollChart pollChart1">&nbsp;</li>'."\n",$key,$val);
于 2012-11-19T11:27:59.483 回答