通过密钥直接访问XML节点 [英] Accessing a XML node directly via a key

查看:94
本文介绍了通过密钥直接访问XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$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();等等.我得到了我想要的数据.

When I print out $currentIndex on each iteration, I get 0, 1, 2, 3, 4, etc. When I hard code $items[0]->asXML(); $items[1]->asXML(); $items[2]->asXML(); etc. I get the data I want.

但是当我像在第一个代码段中那样循环时,它会打印出项目0、2、4等.

But when I loop like I do in the first code segment, it prints out items 0, 2, 4, etc.

这怎么可能?是什么原因造成的?

How is that possible and what could be causing this?

谢谢, 瑞安

添加的信息:

这是它的主要部分:

$totalItems = 45;
$keepItems = 10;
$currentIndex = 0;

while($totalItems > $keepItems)
{
    $totalItems -= 1;
    print_r($xml->list->item[$currentIndex]);
    $currentIndex += 1;
}

我只是在一个单独的文件中尝试过,并且在该实例中有效:

I just tried this in a separate file and it worked in that instance:

$xml = simplexml_load_file($xmlPath);
$items = $xml->list->item;

$counter = 45;
$display = 0;

while($counter > 4)
{
    echo $items[$display]->asXML();

    $display += 1;
    $counter -= 1;
}

所以我的其他代码正在使这种情况发生.我也将不得不对其进行更多研究,但是可以肯定的是,没有什么明显的.

So something in my other code is making this happen. I will have to look at it some more as well, but it's for sure nothing obvious.

谢谢, 瑞安

添加的信息2:

好的,我确定了导致这种其他每个人"综合症的代码行:)

OK, I determined the line of code that causes this "every other one" syndrome :)

unset($items[$currentIndex]);

我的想法是一旦使用数据就删除/取消设置一个项目,但它似乎无法按我预期的方式工作-有人知道为什么吗?为什么要取消未显示的内容?

The thought was to remove/unset an item once I used the data, but it doesn't seem to work the way I expected -- does anybody have an idea of why? Why is it unsetting something it hasn't displayed?

谢谢, 瑞安

推荐答案

Why is it unsetting something it hasn't displayed?这不是您的情况.当您取消设置已处理的项目时,数组数据正在移位...索引1处的前一个元素获得索引0,2移至1,依此类推.因此,如果您在未设置$ element [0]后访问$ element [1],您将获得位于$ element [2]位置的元素,因为前一个$ element [1]移至$ element [0]且$ element [2]到$ element [1].

Why is it unsetting something it hasn't displayed? That's not what is happening in your case. When you unset the processed item, the array-data are shift... the former element at index 1 get the index 0, 2 moves to 1 and so on. So if you access $element[1] after you have unset $element[0] you'll get the element that was at position $element[2], because the former $element[1] moved to $element[0] and $element[2] to $element[1].

如果您始终取消设置已处理的元素,则可以通过在每次迭代中访问$ element [0]来实现,如果数组为空,则可以取消.

If you always unset the processed element, you can do it by accessing $element[0] on each iteration an cancel if the array is empty.


// ...
while ($array) {               // same as count($array)
  $currentElement = $array[0];
  // do something
  unset($array[0]);
}
// ...

这篇关于通过密钥直接访问XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆