【问题标题】:How to buid array and display random values?如何构建数组并显示随机值?
【发布时间】:2016-03-06 20:42:18
【问题描述】:

:) 我无法为数组编写代码。示例:

我想要页面并使用包含数组的导入文件。在数组中我想放入新行注释示例:

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!

【问题讨论】:

  • 你想显示一个名字和一个评论?它们都是随机的吗?
  • foreach($array_names as $value){echo $value. "Was write comments &lt;br&gt;";} 之类的???

标签: php arrays random


【解决方案1】:

如果您知道从 min 到 max 的每个键都表示在数组中,您可以像这样选择一个随机值:

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

如果数组中有其他类型的键,那么最简单的方法是在执行相同操作之前创建一个具有顺序键的新数组。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多