简体   繁体   English

注意:未定义偏移量:#从数组中检索和删除值时

[英]Notice: Undefined offset: # when retrieving and removing values from array

I sometimes (not all the time) get this Notice: Undefined offset: # error 我有时(并非一直)收到此Notice: Undefined offset: #错误

I have an array of words. 我有很多话。 I am randomly selecting a word from this array and then deleting it. 我从此数组中随机选择一个单词,然后将其删除。 The word that I retrieve from the word array is then placed into another array. 然后将从单词数组中检索到的单词放入另一个数组中。

$numberOfWords = $_POST['number_of_words'];
$words = array('an', 'array', 'of', 'words', 'to', 'select', 'from');
$selectedWords = array();

for($i = 0; $i < $numberOfWords; $i++) {
  $wordAt = rand(0, count($words) - 1);
  $word = $words[$wordAt];
  array_push($selectedWords, $word);
  unset($words[$wordAt]);
}

Any ideas? 有任何想法吗?

Thanks! 谢谢!

The issue is that unsetting an array element does not magically renumber the array keys. 问题在于,取消设置数组元素不会神奇地重新编号数组键。 You wind up with a hole in the array. 您在阵列中有一个洞。 Your random number generator doesn't take this into account, and you will wind up selecting the same index multiple times causing your undefined index notice. 您的随机数生成器没有考虑到这一点,您最终会多次选择相同的索引,从而导致未定义的索引通知。 You can easily pick out a random array element using array_rand : 您可以使用array_rand轻松选择随机数组元素:

for($i = 0; $i < $numberOfWords; $i++) {
  $word = array_rand($words);
  array_push($selectedWords, $words[$word]);
  unset($words[$word]);
}

After unset an array element, we need to rebuild the array index using array_values : unset数组元素后,我们需要使用array_values重建数组索引:

$numberOfWords = $_POST['number_of_words'];
$words = array('an', 'array', 'of', 'words', 'to', 'select', 'from');
$selectedWords = array();

for($i = 0; $i < $numberOfWords; $i++) {
  $wordAt = rand(0, count($words) - 1);
  $word = $words[$wordAt];
  array_push($selectedWords, $word);
  unset($words[$wordAt]);
  $words = array_values($words);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM