0

here's my code, which displays the results I'm after, but is it possible to list them by order or

    $xml = simplexml_load_file('racing.xml');

    foreach ($xml->sport[0]->event_path->event_path as $gameinfo):

    $description        =   $gameinfo->description;
    $getdate            =   $gameinfo->event['date'];
    $event_id           =   $gameinfo->event['id'];
    $date               =   substr($getdate,0,10);

The code

    <?=substr($description, -5)?>

leaves me with the variable as times, ie: 14:40, 15:50: 14:20: 18:40 etc etc, but they are shown in the order of the XML rather than by time.

Is there a line of code I can include to sort the results by the date variable?

hakre
  • 193,403
  • 52
  • 435
  • 836
Kris
  • 15
  • 4

3 Answers3

0

PHP has very useful sort function with ability to define user comparison function. See the link: http://www.php.net/manual/en/function.uasort.php

barbashov
  • 542
  • 3
  • 9
  • Struggling to get my head around how to apply that to my code though, I'll have a look tomorrow with fresh eyes! Thanks! – Kris Apr 04 '13 at 16:20
0

First some general hint to improve your code:

foreach ($xml->sport[0]->event_path->event_path as $gameinfo):

Is a bad idea. Instead I make yourself a present and give a new variable (you can thank me later):

$gameinfos = $xml->sport[0]->event_path->event_path;
foreach ($gameinfos as $gameinfo):

So now you want to sort the $gameinfos. Problem here is that those are an iterator and not an array. The uasort function (and all the other array sort functions) will not help you any further. Luckily this has been outlined already, you can convert the iteration into an array:

$gameinfos = iterator_to_array($gameinfos, FALSE);

Now $gameinfos is an array that can be sorted. To do that obtain the values that define the sort-order (of which $gameinfos should be sorted for), I assume it's the time substr($description, -5) you've written above:

$order = array();
foreach ($gameinfos as $game) 
    $order[] = substr($game->description, -5)
;

array_multisort($order, $gameinfos);

// $gameinfos are sorted now.
Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
0

Thanks for your time! I now have my code as:

    $xml = simplexml_load_file('racing.xml');

    $gameinfos = $xml->sport[0]->event_path->event_path;
    foreach ($gameinfos as $gameinfo):

    $gameinfos = iterator_to_array($gameinfos, FALSE);

    $order = array();
    foreach ($gameinfos as $game) 
    $order[] = substr($game->description, -5) ;

    array_multisort($order, $gameinfos);

    // $gameinfos are sorted now.

    $description        =   $gameinfo->description;
    $getdate            =   $gameinfo->event['date'];
    $event_id           =   $gameinfo->event['id'];
    $date               =   substr($getdate,0,10);

This is only returning one result though, I'm thinking I've gonewrong some where along the line?

Kris
  • 15
  • 4