Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

How to order XML/PHP array?

Hello, I am struggling to order an xml. Here is an example of the structure of the XML:

<Events TimeStamp="05/11/2014 09:16:52">
<Event Name="Singin' In The Rain" EventDate="2015-07-14 19:30:00" StartSaleDate="2014-11-24 08:30:00" EndSaleDate="2015-07-14 19:30:00" />
<Event Name="Singin' In The Rain" EventDate="2015-07-19 19:30:00" StartSaleDate="2014-11-24 08:30:00" EndSaleDate="2015-07-19 19:30:00" />
<Event Name="Singin' In The Rain" EventDate="2015-07-03 19:30:00" StartSaleDate="2014-11-24 08:30:00" EndSaleDate="2015-07-19 19:30:00" />
<Event Name="Singin' In The Rain" EventDate="2015-07-08 19:30:00" StartSaleDate="2014-11-24 08:30:00" EndSaleDate="2015-07-19 19:30:00" />
</Events>

I am looking to order them by EventDate. I can turn it into a php array if that helps but I am still struggling to order that in a similar way.

Any help would be greatly appreciated.

Thank you

Josh

1 Answer

I have sorted my own issue:

/* Load XML file */
$event_xml = events.xml;
$event_xml = simplexml_load_file($event_xml)
;
/* Create new empty array */
$events = array();

/* Load XML item attributes into new array */
foreach($loadXML as $event) {

        $events[] = array(
                'Name'             => (string)$event['Name'],
                'EventDate' => (string)$event['EventDate'],
                .... etc
}

/* Function to order array by column */
function compare_eventdate($a, $b)    {
                return strnatcmp($a['EventDate'], $b['EventDate']);
              }

usort($events, 'compare_eventdate');

If anyone has any amends to this please let me know. Thanks