我需要根据array_rand()的先前结果回显一系列四个字符串。到目前为止,我有这个:
<?php
$titles = array('title1','title2','title3','title4');
$title1_words = array('word1','word2','word3','word4','word5','word6','word7');
$title2_words = array('word1','word2','word3','word4','word5','word6','word7');
$title3_words = array('word1','word2','word3','word4','word5','word6','word7');
$title4_words = array('word1','word2','word3','word4','word5','word6','word7');
$rand_title = array_rand($titles, 1);
echo $rand_title . "<br>";
//print 4 random words from one group
$rand_words = array_rand($title1_words, 4);
echo $title1_words[$rand_words[0]] . "<br>";
echo $title1_words[$rand_words[1]] . "<br>";
echo $title1_words[$rand_words[2]] . "<br>";
echo $title1_words[$rand_words[3]] . "<br>";
?>
我需要输出类似于:
&#34; Title 2
word2,word4,word5,word7&#34;,其中这些单词实际上与主标题相关。
(单词因组而异。我只是使用相同的名称来使其更容易理解。)
每次刷新页面时都应该回显不同的值。
//编辑以获得进一步说明//
当它刷新时,它应该回显另一个标题和另一组与该标题相关的4个单词。
P.S。:Srsly,为什么下来投票?至少解释一下。答案 0 :(得分:1)
正如评论中所解释的,处理这个问题的最好方法是将你的单词存储在一个二维数组中,如下:
$words = array(
'title1' => array('word1','word2','word3','word4','word5','word6','word7')),
'title2' => array('word1','word2','word3','word4','word5','word6','word7')),
'title3' => array('word1','word2','word3','word4','word5','word6','word7')),
'title4' => array('word1','word2','word3','word4','word5','word6','word7')),
);
然后使用$words[$titles[$rand_title]]
作为您的单词子阵列。
但是,如果你不能(或绝对不想)使用二维数组,你总是可以使用 variable variables :
<?php
$titles = array('title1','title2','title3','title4');
$title1_words = array('word1','word2','word3','word4','word5','word6','word7');
$title2_words = array('word1','word2','word3','word4','word5','word6','word7');
$title3_words = array('word1','word2','word3','word4','word5','word6','word7');
$title4_words = array('word1','word2','word3','word4','word5','word6','word7');
$rand_title = array_rand($titles, 1);
echo $rand_title . "<br>";
$title = $titles[$rand_title]; // should be title2, for instance
$words_array = ${$title . '_words'}; // should be $title2_words, for instance
$rand_words = array_rand($words_array, 4);
echo $words_array[$rand_words[0]] . "<br>";
echo $words_array[$rand_words[1]] . "<br>";
echo $words_array[$rand_words[2]] . "<br>";
echo $words_array[$rand_words[3]] . "<br>";
?>