1

I'm using the below code to output train departure times. But I can't get them sorted by time of departure. I'm new to coding so not sure how to solve this. How can I use natural-sort or some other solution to get this sorted?

<?php
    $url = 'http://api.sl.se/api2/realtimedepartures.json?key=xxxx&siteid=9192&timewindow=30';
    $jsondata = file_get_contents($url);

    $json = json_decode($jsondata,true);


    foreach ($json['ResponseData']['Metros'] as $metro) {
        if ($metro['DisplayTime'] != "Nu") {
            $output .= "<ul><li><strong>".$metro['DisplayTime'].".</strong>  </li>";
        } else {
            $output .= "<ul><li><strong>".$metro['DisplayTime']." avgår </strong></li>";
        }
        $output .= "<li>".$metro['GroupOfLine']."</li>";
        $output .= "<li> nr ".$metro['LineNumber']."  </li>";

        $output .= "<li> till<strong> ".$metro['SafeDestinationName']."</strong></li></ul>";

   }

   echo $output;
?>

Example of the output can be viewed at http://beta.tunnelbanakarta.se/slussen

Ivan
  • 2,463
  • 1
  • 20
  • 28
P.Membas
  • 33
  • 6

1 Answers1

0

You could use the usort() function to sort the array.

<?php
function cmp($a, $b)
{
    if ($a['DisplayTime'] == $b['DisplayTime']) {
        return 0;
    }
    return ($a['DisplayTime'] < $b['DisplayTime']) ? -1 : 1;
}

$url = 'http://api.sl.se/api2/realtimedepartures.json?key=xxxx&siteid=9192&timewindow=30';
$jsondata = file_get_contents($url);

$json = json_decode($jsondata,true);

usort($json['ResponseData']['Metros'], "cmp");

foreach ($json['ResponseData']['Metros'] as $metro) {
    if ($metro['DisplayTime'] != "Nu") {
        $output .= "<ul><li><strong>" . $metro['DisplayTime'] . ".</strong>  </li>";
    } else {
        $output .= "<ul><li><strong>" . $metro['DisplayTime'] . " avgår </strong></li>";
    }
    $output .= "<li>" . $metro['GroupOfLine'] . "</li>";
    $output .= "<li> nr " . $metro['LineNumber'] . "  </li>";

    $output .= "<li> till<strong> " . $metro['SafeDestinationName'] . "</strong></li></ul>";
}

echo $output;
?>

Should work but it's been a long time since I used these function (or PHP for that matter) so best look into it to see if you can find a cleaner way.

ScottBoy
  • 16
  • 2
  • Great! Thanks a lot, it works. But this still leaves me with one issue. The trains that depart ($metro['DisplayTime'] != "Nu") are shown last. Nu is Swedish for Now so it would be great if it was possible to show the "Nu" values before the numbered values. – P.Membas May 06 '16 at 11:53
  • I made a "quick fix" and set the "now" departing times to display:none, it's not really relevant data for the user. Thanks again for solving my issue. @ScottBoy – P.Membas May 06 '16 at 12:12
  • Glad I could help. You could try adding `if ($a['DisplayTime'] == 'Nu') return -1;` to the start of the cmp function to move all the Nu ones to the top. – ScottBoy May 06 '16 at 12:17