douyong4842 2014-11-12 05:12
浏览 21
已采纳

使用array_rand PHP的未定义索引

I am trying to re-create an array by choosing random elements of an existing array using array_rand().

However, when using the following code and spitting out the array, I am getting an undefined index error in reference to it.

The array is $city_users_trimmed.

PHP code:

$rand = array_rand($city_users_trimmed, 1);

$data = array($city_users_trimmed[$rand[0]]);

I know that $city_users_trimmed has at least 1 element in it, so there is no reason I see why this wouldn't be working.

I tested it by running:

$data = array($city_users_trimmed[0]);

which works, so there is at least one element in the $city_users_trimmed array. Is there anything you see that is causing this issue? Thank you.

  • 写回答

3条回答 默认 最新

  • dtd5644 2014-11-12 05:19
    关注

    Check http://php.net/manual/en/function.array-rand.php

    When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned.

    So in $rand is your key, not in $rand[0]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持