Sort XML via attribute value PHP

后端 未结 6 787
忘掉有多难
忘掉有多难 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:40

    If you have many elements like this

    $string = <<
    
    
    
    
    
    
    
    
    
    
    
    EOS;
    

    You can use foreach:

    $xml = simplexml_load_string($string);
    
    function sort_trees($t1, $t2) {
        return $t1['order'] - $t2['order'];
    }
    
    foreach($xml->talentTrees as $talentTrees){
        foreach($talentTrees->tree as $tree){
        $trees[]= $tree;
        }
        usort($trees, 'sort_trees');
        print_r($trees);
        unset($trees);
    }
    

    output:

    Array
    (
        [0] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [name] => Baseball
                                [order] => 0
                            )
    
                    )
    
                [1] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [name] => Frisbee
                                [order] => 1
                            )
    
                    )
    
                [2] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [name] => Football
                                [order] => 2
                            )
    
                    )
    
            )
    
        [1] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [name] => Frisbee2
                                [order] => 0
                            )
    
                    )
    
                [1] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [name] => Football2
                                [order] => 1
                            )
    
                    )
    
                [2] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [name] => Baseball2
                                [order] => 2
                            )
    
                    )
    
            )
    
    )
    

    For another example: https://stackoverflow.com/a/44379495/3506219

提交回复
热议问题