0

I can't find an exact duplicate of this question, as my nodes are numerical keys.

I need to sort this xml by date - newest first:

[article] => Array
    (
        [0] => SimpleXMLElement Object
            (
                [value] => some value
                [date] => 2012-08-13 18:54:09
            )

        [1] => SimpleXMLElement Object
            (
                [id] => some more value
                [date] => 2012-08-09 10:24:06
            )

        [2] => SimpleXMLElement Object
            (
                [id] => another value
                [date] => 2012-08-11 20:45:44
            )
     )

How can I best do that - possibly WITHOUT turning the XML into a PHP array and sorting it then.

Tomi Seus
  • 1,131
  • 2
  • 13
  • 28
  • 2
    Both http://stackoverflow.com/questions/11940042/sort-multidimensional-xml-with-php-by-date and http://stackoverflow.com/questions/3998722/how-to-sort-a-multi-dimensional-xml-file seems fine to me. If you don't want the `xsort()` and `array_multisort()`, then just use `usort()` with a custom function comparing the date, no? – Savageman Aug 13 '12 at 18:35
  • i tried it but it doesn't work as the arrays are xml objects – Tomi Seus Aug 14 '12 at 13:02

1 Answers1

0

From your sample, it looks like you have an array of objects already, so usort would work fine.

The callback would look something like this:

function compare_node_dates($a, $b)
{
    return
        strtotime((string)$b->date)
        -
        strtotime((string)$a->date);
}

However, if your outermost variable isn't actually an array, there is no way I'm aware of doing this without creating an array, sorting that, and using that to construct brand new XML.

IMSoP
  • 89,526
  • 13
  • 117
  • 169