使用随机选择的数组字符串来确定输出时其他两个html表格单元格的值


Use an array string that is chosen randomly to determine the value of two other html table cells on output

标题是我能解释的最简单的方式。这是课堂作业,但我已经做了几个小时了,需要一些帮助。基本上,我有一串十二生肖。在页面加载(或刷新)时,将随机选择其中一个符号,并在3列一行表的单元格中显示为文本。下一个单元格应该是一个匹配的图像,然后最后一个单元格应该是2016年中国生肖预测,作为文本。

问题是,我需要匹配图像和文本块与随机生成的标志。这是我现在的代码…它是随机选择文本的第一个单元格和图像的第二个单元格,当然,很少是相同的…

我已经尝试运行它调用当前$ran,它显示开关默认消息。

$pic = $ran一起运行,每次都返回猴子的图像,这是第一种选择

你可以在我的网站上看到它。Taskdollar.com/misc-code.php

如有任何帮助,不胜感激

<?php
    function array_random($arr, $num = 1) {
        shuffle($arr);
        $r = array();
        for ($i = 0; $i < $num; $i++) {
             $r[] = $arr[$i];
    }
    return $num == 1 ? $r[0] : $r;
}
?>
<center>
<table width="80%" border="2px solid green" cellpadding="1px">
<th width="15%"><h1>Chinese Zodiac Sign</h1></th>
<th width="15%"><h1>Chinese Zodiac Sign Image</h1></th>
<th width="70%"><h1>Chinese Zodiac 2016 Predictions</h1></th>
<tr>
<td style="text-align: center; font-size: 36px"><h1><?php
$a =  array("Monkey","Rooster","Dog","Pig","Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Sheep");
    $ran = print_r(array_random($a, TRUE)); ?></h1></td>
<td><center><?php $pic = array_random($a, TRUE);
        switch($pic) {
            case "Monkey":
                echo "<img src='monkey.gif'>";
                break;
            case "Sheep":
                echo "<img src='sheep.gif'>";
                break;
            case "Dragon":
                echo "<img src='dragon.gif'>";
                break;
            case "Ox":
                echo "<img src='ox.gif'>";
                break;
            case "Pig":
                echo "<img src='pig.gif'>";
                break;
            case "Rabbit":
                echo "<img src='rabbit.gif'>";
                break;
            case "Rat":
                echo "<img src='rat.gif'>";
                break;
            case "Rooster":
                echo "<img src='rooster.gif'>";
                break;
            case "Snake":
                echo "<img src='snake.gif'>";
                break;
            case "Dog":
                echo "<img src='dog.gif'>";
                break;
            case "Horse":
                echo "<img src='horse.gif'>";
                break;
            case "Tiger":
                echo "<img src='tiger.gif'>";
                break;
            default:
                echo "Failed to load. Please refresh your browser.";
                break;  
            }   ?></center></td>
 <td>Case Statements will go here that will choose a block of text to match the sign...</td>
 </tr>
 </table></center>

我认为你需要重组一下你的数据。你这样做是在重复很多工作

$a =  array(
    array("Monkey", "<img src='monkey.gif'>"),
    array("Rooster", "<img src='rooster.gif'>"),
    ...
);

现在,您需要做的就是随机选择一个值

function array_random(Array $array) {
    $rand = mt_rand(0, count($array) - 1);
    return $array[$rand];
}

这样,所有的数据都保存在一起,可以作为一个紧凑的数据结构返回