在PHP上使用foreach和array_slice从数组中获取随机值


Get random values from array on PHP using foreach and array_slice?

如何随机化此代码的结果?

我有一个数组,上面有四个以上的项目,但我只想得到其中的四个,但不按顺序,我该怎么做?可以使用foreach(array_slice??

$i = 0;
foreach(array_slice($items_array,0,4) as $item) {
$output .= 'Item ID:'.$item['id'];
$i++;
}

我的阵列

a:6:{i:0;a:4:{s:5:"title";s:17:"Spedition";s:2:"id";s:11:"ZCXbgH1JDt4";s:3:"url";s:40:"embed/ZCXbgH1JDt4";s:5:"image";s:38:"transport";}i:1;a:4:{s:5:"title";s:77:"DC...... 
$output = array_rand($items_array, 4);

array_rand()

已解决

$item = array_rand($items_array, 4); //get only four at random
$i=0;
while($i<=3) { // instead of 4 you set it at 3 because the counter starts at 0
$output = 'Item ID:'.$items_array[$item[$i]]['id'];             
$i++;
}

从阵列中获取随机值的完美方法

$numbers = range(1, 20);
shuffle($numbers); //this function will shuffle the array value
foreach ($numbers as $number) {
    echo "$number ";
}

一个更好、更简单的解决方案是使用array_rand

$array          =  array("foo", "bar", "hallo", "world");
$rand_keys  =  array_rand($array,1);
echo $array[$rand_keys];

这应该为您完成。

$i = 0;
foreach(array_rand($items_array, 4) as $item) {
  $output .= 'Item ID:'.$item['id'];
  $i++;
}