通过属性值PHP对XML进行排序 [英] Sort XML via attribute value PHP
本文介绍了通过属性值PHP对XML进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个XML文件,该文件要根据属性"order"按顺序循环遍历.
So I have an XML file that I am trying to loop through in order, according to the attribute, "order".
这里是一个例子:
<page>
<talentTrees>
<tree name="Football" order="2">
<tree name="Baseball" order="0">
<tree name="Frisbee" order="1">
</talentTrees>
</page>
我的目标是使用foreach遍历每棵树",但是我想按order属性的顺序阅读它们:棒球,飞盘,足球. (0,1,2).
My goal is to loop through each "tree" using foreach, but I want to read them in order of the order attribute: Baseball, Frisbee, Football. (0,1,2).
抱歉,英语不好,不是我的母语.
Sorry for poor English, not my first language.
推荐答案
这应该为您提供想要的东西:
This should give you what you want:
$string = <<<EOS
<page>
<talentTrees>
<tree name="Football" order="2" />
<tree name="Baseball" order="0" />
<tree name="Frisbee" order="1" />
</talentTrees>
</page>
EOS;
$xml = simplexml_load_string($string);
$trees = $xml->xpath('/page/talentTrees/tree');
function sort_trees($t1, $t2) {
return strcmp($t1['order'], $t2['order']);
}
usort($trees, 'sort_trees');
var_dump($trees);
$trees
现在按订单属性排序.
$trees
are now sorted by the order attribute.
这篇关于通过属性值PHP对XML进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文