Sorting an array of SimpleXML objects

后端 未结 5 1212

I\'ve read what I\'ve found on Stackoverflow and am still unclear on this.

I have an array of SimpleXML objects something like this:

array(2) {
  [0]         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 00:53

    I guess the people suggesting to use SimpleDOM would be me. :)

    I've written SimpleDOM::sort() exactly for that situation, because in order to sort SimpleXMLElements by an arbitration expression (or arbitrary expressions) you need to use array_multisort() which is boring and won't teach you anything useful.

    Here's the short version of how it works: first you create a proxy array of key=>value pairs corresponding to each SimpleXMLElement and the value with which they'll be sorted. In your example, if you want to sort them by , the array would be array(21, 56). Then you call array_multisort() with the "proxy array" as first argument, followed by any number of sorting modifiers such as SORT_DESC or SORT_NUMERIC then finally the array you want to sort, which will be passed by reference.

    You will end up with something like that:

    $nodes = array(
        new SimpleXMLElement('Andrew21'),
        new SimpleXMLElement('Beth56')
    );
    
    function xsort(&$nodes, $child_name, $order = SORT_ASC)
    {
        $sort_proxy = array();
    
        foreach ($nodes as $k => $node)
        {
            $sort_proxy[$k] = (string) $node->$child_name;
        }
    
        array_multisort($sort_proxy, $order, $nodes);
    }
    
    xsort($nodes, 'name', SORT_ASC);
    print_r($nodes);
    
    xsort($nodes, 'age', SORT_DESC);
    print_r($nodes);
    

    But really, instead of burdening yourself with more code you'll have to maintain and possibly ending up rewriting array_multisort() in userspace, you should leverage existing solutions. There's nothing interesting in such a sorting algorithm/routine, your time would be better spent on something that doesn't already exist.

提交回复
热议问题