2016-03-06 21 views
0

:) 我无法编写数组的代码。例如:如何构建数组并显示随机值?

我想要页面并使用包含导入文件的数组。在阵列我想放在新行评论示例:

id-1 = first one 
id-2 = second one 
etc... 
id-333 = other comment 

接下来,我想显示从数组中的随机值。例如:

Mr. Bad coder write comment: 
first one 

这是怎么回事?我读了很多的教程和我的代码如下所示:

array.php文件:

$array_names = array(
    '1' => 'Mike', 
    '2' => 'John', 
    '3' => 'Ana', 
); 

文件来显示阵列:

<?php 
include('array.php'); 
echo $array_names; ?> was write a comment! 
+0

你想显示一个名字和一个评论?他们都是随机的吗? – trincot

+0

'foreach($ array_names as $ value){echo $ value。 “写评论
”;}'这样的事情? – devpro

回答

0

如果你知道,从分钟每个键以最大值表示在阵列中,您可以只选择一个像这样的随机值:

$randomKey = mt_rand($min, $max); 
echo $array_names[$randomKey] 

如果你hav在数组中其他类型的键然后最简单的方法是在做同样的事情之前创建一个具有顺序键的新数组。

+1

array_rand()是这个更好的方法 – 2016-03-06 20:58:19

+0

不太确定,请阅读顶端的评论: http://php.net/manual/en/function.array-rand.php – purpleninja