Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/237.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在for循环之后,返回的数组是错误的_Php_Arrays_For Loop - Fatal编程技术网

Php 在for循环之后,返回的数组是错误的

Php 在for循环之后,返回的数组是错误的,php,arrays,for-loop,Php,Arrays,For Loop,我有这样的想法: $n = 2; $items = array(); $result = array(); // new array with random items $random_items = array_rand( $items, $n ); for( $f=0; $f<=$n; $f++ ) { $result[] = $items[$random_items[$f]]; } 这工作正常。。。但是,如果我将$n设置为1,则脚本没有工作或工作不正确 如果$n==2(

我有这样的想法:

$n = 2;

$items = array();

$result = array(); // new array with random items

$random_items = array_rand( $items, $n );

for( $f=0; $f<=$n; $f++ ) {
  $result[] = $items[$random_items[$f]];
}
这工作正常。。。但是,如果我将
$n
设置为
1
,则脚本没有工作或工作不正确

如果$n==2(或更多),则结果数组的最后一个元素的值为空

Array ( [0] => 20141125-17826a4b34.png [1] => 20141125-27fe57561d.jpg [2] => )
如果$n==1(正好),则结果数组如下

Array ( [0] => [1] => ) 
结果数组的格式应与items数组的格式相同,但仅包含$n个随机项

提前谢谢

工作

if( $n > 1 ) {
  for( $f=0; $f<$n; $f++ ) {
    $result[] = $items[$random_items[$f]];
  }
}
elseif( $n == 1 ) {
  $result[0] = $items[$random_items];
}
if($n>1){

对于($f=0;$f您应该
$f<$n
而不是
$f问题#1:
$f@RafcioKowalsky是的,我在下面添加了解释..对于
$n=1
array\u rand()
只返回一个值,不返回值的数组。
if( $n > 1 ) {
  for( $f=0; $f<$n; $f++ ) {
    $result[] = $items[$random_items[$f]];
  }
}
elseif( $n == 1 ) {
  $result[0] = $items[$random_items];
}
for( $f=0; $f < $n; $f++ ) {
  $result[] = $items[$random_items[$f]];
}