Sort XML via attribute value PHP

后端 未结 6 811
忘掉有多难
忘掉有多难 2020-12-01 20:25

So I have an XML file that I am trying to loop through in order, according to the attribute, \"order\".

Here is an example:




        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 20:32

    This should give you what you want:

    $string = <<
    
    
    
    
    
    
    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 are now sorted by the order attribute.

提交回复
热议问题