【问题标题】:After for-loop, returned array is wrongfor循环后,返回的数组是错误的
【发布时间】:2015-01-25 08:09:40
【问题描述】:

我有类似的东西:

$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]];
}

$items 有点像

Array ( [0] => file1.jpg [1] => file2.png [2] => file3.jpg ... and so on )

这工作正常...但如果我将 $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];
}

【问题讨论】:

  • 问题 #1:$f&lt;=$n; 应该是 $f&lt;$n;,虽然 foreach($random_items as $f) 会更容易

标签: php arrays for-loop


【解决方案1】:

你应该$f &lt; $n 而不是$f &lt;= $n

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

因为,当您使用 $f &lt;= $n 时,它会运行到 0,1 (when, $n = 1)0,1,2 (when $n = 2) 并且您缺少最后一个索引元素。

当只选择一个条目时,array_rand() 返回随机的键 条目(不是数组)。否则,返回随机条目的键数组。

所以,这意味着,当您使用$n = 1 时,$random_items 只是一个值(不是数组)。例如。

$n = 1, $random_items = 4;

但对于$n &gt;= 2, $random_items = [1, 6, 3, 6];

【讨论】:

  • @RafcioKowalsky 是的,我在下面添加了解释.. 对于 $n = 1 array_rand() 只返回一个值而不是值数组。
猜你喜欢
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多