【发布时间】:2025-12-01 06:45:01
【问题描述】:
$xml = simplexml_load_file($xmlPath);
$items = $xml->list->item;
...
echo $items[$currentIndex]->asXML();
当我在每次迭代中打印出 $currentIndex 时,我会得到 0、1、2、3、4 等。 当我硬编码 $items[0]->asXML(); $items[1]->asXML(); $items[2]->asXML();等等。我得到了我想要的数据。
但是当我像在第一个代码段中那样循环时,它会打印出项目 0、2、4 等。
这怎么可能?是什么原因造成的?
谢谢, 瑞恩
添加信息:
这是它的主要部分:
$totalItems = 45;
$keepItems = 10;
$currentIndex = 0;
while($totalItems > $keepItems)
{
$totalItems -= 1;
print_r($xml->list->item[$currentIndex]);
$currentIndex += 1;
}
我只是在一个单独的文件中尝试了这个,它在那个实例中工作:
$xml = simplexml_load_file($xmlPath);
$items = $xml->list->item;
$counter = 45;
$display = 0;
while($counter > 4)
{
echo $items[$display]->asXML();
$display += 1;
$counter -= 1;
}
所以我的其他代码中的某些东西正在发生这种情况。我还得再看看它,但肯定没有什么明显的。
谢谢, 瑞恩
添加信息 2:
好的,我确定了导致这种“每隔一个”综合症的代码行:)
unset($items[$currentIndex]);
我的想法是在使用数据后删除/取消设置项目,但它似乎没有按我预期的方式工作——有人知道为什么吗?为什么它会取消未显示的内容?
谢谢, 瑞恩
【问题讨论】:
-
你能告诉我们设置
$currentIndex的循环代码吗?您是否需要确保 $currentIndex 是数字而不是字符串?