如何包含一个带有2个变量的随机数组

时间:2012-05-20 17:10:22

标签: php arrays random

我的config.php包含:

$a1="title";
$b1="text";
$a2="title2";
$b2="text2";

我的1.php包括config.php

我需要随机包含($ a1和$ b1)或($ a和$ b)。

我该怎么做? :)

谢谢。

1 个答案:

答案 0 :(得分:1)

如果此数据相关,并且您需要随机设置,请将其存储在数组中:

$sets = array(
    array(
        'title' => 'Some title',
        'text'  => 'Some text here about the title'
    ),
    array(
        'title' => 'Some other title',
        'text'  => 'Some other text here about the title'
    )
);

使用此数组,我们可以选择两个索引:

$sets[0]; // Title: Some title, Text: Some text here about the title
$sets[1]; // Title: Some other title, Text: Some other text here about the title

如果我们想要其中一个,随机,我们可以执行以下操作:

$index = array_rand( $sets, 1 );

这将选择01。在我们的阵列中有更多条目,这个数字的可能性也会增加。然后我们可以使用它来获取我们的一组数据:

$dataSet = $sets[ $index ];

然后显示输出:

echo $dataSet['title'];
echo $dataSet['text'];