[英]PHP get different random array elements
Actually I have this code to get differents elements depending of how many many values $N represents. 实际上,我有这段代码根据$ N代表多少个值来获取differents元素。
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, $N) as $key )
{
echo $my_array[$key];
}
For example if $N = 2
, I will get two random elements and it works fine. 例如,如果
$N = 2
,我将得到两个随机元素,它可以正常工作。
The problem is when $N = 1
, I get the following error: 问题是当
$N = 1
,出现以下错误:
WARNING Invalid argument supplied for foreach()
警告为foreach()提供了无效的参数
Any idea or advice to fix it? 有什么想法或建议要解决吗?
Quick fix is: 快速解决方法是:
$my_array = array('a','b','c','d','e');
// Cast result of `array_rand` to type "array"
foreach((array)array_rand($my_array, $N) as $key)
{
echo $my_array[$key];
}
If array_rand
's 2nd parameter is 1, it returns an element instead of an array containing the elements. 如果
array_rand
的第二个参数为1,它将返回一个元素,而不是包含这些元素的数组。
For example: 例如:
$my_array = array('a','b','c','d','e');
array_rand($my_array, 1); // returns 'b'
array_rand($my_array, 2); // returns ['b', 'd']
You could do this: 您可以这样做:
$randoms = array_rand($my_array, $N);
if ($N == 1) {
$randoms = [$randoms];
}
foreach ($randoms as $key) {
// ...
}
<?php
$my_array = array('a','b','c','d','e');
shuffle($my_array);
if($my_array!=NULL)
{
foreach($my_array as $data)
{
echo $data;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.