在下面的SSCCE中,为什么for
执行的$a
循环不大于3,尽管条件应该让它执行直到$a
变为5。 / p>
最后一句话的输出更加奇怪。
我想要实现的是,我想要删除元素/变量Select one
的{{1}}值的元素,以便生成的数组为:
word
问题是什么弄乱了它,我该怎么做才能解决它?
Array ( [0] => stdClass Object ( [word] => alpha [sentence] => A is the first letter in the word Alpha. ) [1] => stdClass Object ( [word] => beta [sentence] => B is the first letter in the word Beta. ) )
输出:
<?php
$objectOne = new stdClass;
$objectOne->word = 'alpha';
$objectOne->sentence = 'A is the first letter in the word Alpha.';
$objectTwo = new stdClass;
$objectTwo->word = 'beta';
$objectTwo->sentence = 'B is the first letter in the word Beta.';
$objectThree = new stdClass;
$objectThree->word = 'Select one';
$objectThree->sentence = '';
$items = array($objectOne, $objectTwo, $objectThree, $objectThree, $objectThree, $objectThree );
print_r($items);//check
echo '<br><br>count($items) >> '.count($items).'<br><br>';//check
for ($a=0; $a < count($items); $a++) {
echo '<br><br>We are entering index '.$a.'<br><br>';//check
echo '<br>'.$items[$a]->word.'<br>';//check
if ( ($items[$a]->word)=="Select one" ) {
echo '<br>YES if ( ($items['.$a.']->word)=="Select one" ) AT '.$a.' INDEX.<br>';//check
unset($items[$a]);
/**/array_splice($items, $a, 1);
}
echo '<br><br>We are leaving index '.$a.'<br><br>';//check
}
echo '<br><br>AFTER:-<br>';//check
print_r($items);//check
?>
答案 0 :(得分:1)
在执行期间取消设置main键时,使用temp
变量进行迭代。也许,这应该有效: -
$temp = $items;
for ($a=0; $a < count($temp); $a++) {
echo '<br><br>We are entering index '.$a.'<br><br>';//check
echo '<br>'.$items[$a]->word.'<br>';//check
if ( ($items[$a]->word)=="Select one" ) {
echo '<br>YES if ( ($items['.$a.']->word)=="Select one" ) AT '.$a.' INDEX.<br>';//check
unset($items[$a]);
/**/array_splice($items, $a, 1);
}
echo '<br><br>We are leaving index '.$a.'<br><br>';//check
}
答案 1 :(得分:1)
条件并非总是如此。 for循环中的条件会在每次迭代中重新计算数组的大小。每当删除一个项目时,数组的长度都会改变。
每次检查条件时$a
和count($items)
的值如下:
$a | count($items) | $a < count($items)
---------------------------------------
0 | 6 | true
1 | 6 | true
2 | 6 | true
3 | 5 | true -- $items[2] was removed
4 | 4 | false -- $items[3] was removed
您应该将数组的大小存储在变量中并使用它。此外,由于array_splice
不会保留数字键,因此在尝试访问$items[4]
和$items[5]
时,最终会收到未定义的偏移通知。该行不是必需的。
$count = count($items);
for ($a=0; $a < $count; $a++) {
更好的是,您可以使用foreach
代替for
并使用$item
代替$items[$a]
:
foreach ($items as $a=>$item) {
echo '<br><br>We are entering index '.$a.'<br><br>';//check
echo '<br>'.$item->word.'<br>';//check
...
unset($items[$a]); //can't use $item because it is a copy and not a reference