PHP simplexml 反向
有没有办法反向循环 simpleXML 中加载的 xml? 假设我有以下 xml
$string ="<items>
<item>1</item>
<item>2</item>
<item>3</item>
</items>";
$xml = simplexml_load_string($string);
有没有办法反转 $xml 以便我在执行 foreach 时得到第 3 项
Is there any way to loop through an xml loaded in simpleXML in reverse?
say if i have the following xml
$string ="<items>
<item>1</item>
<item>2</item>
<item>3</item>
</items>";
$xml = simplexml_load_string($string);
is there any way to reverse $xml so that i get item 3 when i do a foreach
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
假设OP是一个初学者,只对解决方案感兴趣,我建议使用
xpath()
来获取元素,并使用array_reverse()
来反转它们的顺序:注意:XPath “item” 获取当前元素的直接子元素的所有
元素。Assuming the OP is a beginner only interested in a solution I'd recommend using
xpath()
to get the elements andarray_reverse()
to reverse their order:Note: the XPath "item" grabs all
<item/>
elements that are the direct children of current element.使用 simplexml:
打印:
另一个例子:
它有点冗长,并且使用了更强大的
DomDocument
如果您确实想要,则不是 SimpleXml ;)打印:
With simplexml:
prints:
Another expample:
It's a little verbose and it uses the more powerful
DomDocument
and not SimpleXml if you really want to ;)prints:
这对我来说效果很好:
输出:
This works fine for me:
Output:
由于 PHP 中的
迭代器
没有 < code>previous 风格的方法,简短的答案是否定的。您可以将它们读入数组,然后反转数组,但这不会直接向后迭代。一种选择是创建一个 ReverseIterator,在其中包装一个常规迭代器,然后向后遍历它。但这可能会出现问题,因为您不知道迭代器是否有结束(您可以在 SPL)。
所以不,你不能。你唯一的选择是做这样的事情:
Since
Iterators
in PHP have noprevious
style method, the short answer is no. You could read them into an array and then reverse the array, but that wouldn't be directly iterating backwards.One option would be to create a ReverseIterator, where you wrap a regular iterator and then traverse it backwards. But that might get problematic since you don't know if a iterator has an end (You can see some examples that don't in the SPL).
So no, you can't. Your only option would be to do something like this:
$xml->item
是一个数组。使用数组排序函数。编辑:好的,没有办法做到这一点。你必须先创建一个数组。
(不再测试)
$xml->item
is an array. Use array sorting functions.EDIT: Ok, there is no way to do this. You have to make an array first.
(no testing again)