用SimpleXML / XPath排序XML? [英] Sorting XML with SimpleXML/XPath?

查看:142
本文介绍了用SimpleXML / XPath排序XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些XML,例如:

I have some XML, say:

<Backgrounds>
  <Background>
    <Uses>14</Uses>
  </Background>
  <Background>
    <Uses>19</Uses>
  </Background>
  <Background>
    <Uses>3</Uses>
  </Background>
</Backgrounds>

如何从最低排序XML 使用 到最高?

How can I sort the XML from lowest Uses to highest?

也许是一个xpath表达式?

Maybe an xpath expression?

另外,我只是检索底部2 背景 s ,或最近添加的

Also, how could I just retrieve the bottom 2 Backgrounds, or the ones most recently added?

推荐答案

使用SimpleXML / XPath排序的示例



Examples of sorting with SimpleXML/XPath


最低 使用 最高?

要排序从最低到最高的元素列表,您需要创建一个这些元素的数组,然后对该数组进行排序。 xpath表达式可用于获取要排序的元素数组以及数组排序的数据(sort-key)。

To sort a list of elements from lowest to highest, you need to create an array of those elements and then sort that array. The xpath expression can be used to obtain both, the array of elements to be sorted as well as the data that array is sorted on (sort-key).

与您的XML和 使用 children作为sort-value,它的工作原理如下:

With your XML and the Uses children as sort-value, it works the like the following:

$elements = $xml->xpath('/*/Background');
$sortKeys = $xml->xpath('/*/Background/Uses');

array_multisort($sortKeys, SORT_NUMERIC, SORT_ASC, $elements);

foreach($elements as $i => $element) {
    echo $i, ' ', $element->asXML(), "\n";
}

其中:

0 <Background>
    <Uses>14</Uses>
  </Background>
1 <Background>
    <Uses>19</Uses>
  </Background>
2 <Background>
    <Uses>3</Uses>
  </Background>

请参阅 array_multisort() 我如何在php 中排序一个多维数组。

See array_multisort() and "How do I sort a multidimensional array in php".


另外,我如何才能检索底部的2 背景 s 或最近添加的

这可以单独使用xpath:

This is possible to do with xpath alone:

$bottomTwo = $xml->xpath('/*/Background[position() > count(/*/Background) - 2]');

如果最近添加的意思是顶部而不是底部的

And if most recently added mean the ones on top and not on the bottom:

$topTwo = $xml->xpath('/*/Background[position() < 3]');  

这篇关于用SimpleXML / XPath排序XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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