【问题标题】:PHP Warning: array_rand() expects parameter 1 to be array, boolean givenPHP 警告:array_rand() 期望参数 1 是数组,给定的布尔值
【发布时间】:2016-09-27 01:17:46
【问题描述】:

我的代码:

$input = array("1", "2", "3", "4", "5", "6", "8", "15", "22");
$value1=$input[array_rand($input)];

我想随机化给定的数字并将其中的一个数字返回到“$input”,但出现错误: "PHP 警告:array_rand() 期望参数 1 是数组,布尔值在...中给出...

触发此错误的行在这里:

$value1=$input[array_rand($input)];

如何解决这个错误?

?

谢谢!

【问题讨论】:

  • ..因为$input是布尔类型,而不是数组。 RTM
  • 因为我们不知道 $input 是什么,也不知道它来自哪里,所以我们无能为力。事实上,$input 不是一个数组。
  • @Jeff 哦,太好了,非常感谢您提供的信息,那么如何才能不一遍又一遍地在我的服务器上读取此错误?
  • 你是认真的吗?您甚至阅读了错误消息吗?再清楚不过了。
  • @Sverri M. Olsen 很抱歉,但我不知道该怎么做才能解决这个问题。

标签: php arrays boolean


【解决方案1】:

这应该可行:

$input = ["1", "2", "3", "4", "5", "6", "8", "15", "22"];

$randomInputIndex = rand(0, count($input)); // Returns any integer between 0 and 8 in your case
$randomInputValue = $input[$randomInputIndex];
// $input[0] returns 1
// $input[1] returns 2
// $input[7] returns 15
// $input[8] returns 22

或者干脆使用:

$input = ["1", "2", "3", "4", "5", "6", "8", "15", "22"];

$randomInputValue = array_rand($input);

阅读更多关于 PHP 数组的信息here

【讨论】:

  • 我认为事情是这样的,因为如果我没记错的话,当我将代码从“mysql”编辑到“mysqli”时,我会遇到相同类型的“布尔”错误......我是肯定会奏效!非常感谢 JasonK!
  • 我需要 $input 只是 1 给定的随机数:“1”,“2”,“3”,“4”,“5”,“6”,“8”, “15”、“22”
  • 这两个例子都应该做到这一点……你试过了吗?
  • 我猜第二个版本对我有用,不需要计算,但重要的是从给定的数字中随机给我一个数字:“1”、“2”、“ 3”、“4”、“5”、“6”、“8”、“15”、“22”等。非常感谢先生。杰森克!
  • 没问题,如果解决了您的问题,请采纳。祝你好运。
【解决方案2】:

正是您需要的方式!

$input = array("preto", "vermelho", "laranja", "roxo", "abacate", "pera", "uva");


$random = array_rand($input, 1);
print_r($input[$random]);

结果随机唯一:

拉拉尼亚

【讨论】:

    【解决方案3】:
    $value1= $input->random(number);
    

    ps: number = 你想要获取的元素个数,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多