I have a PHP function that talks to another API for real-time train information to get data from it. It makes the call and parses the XML data to JSON but when there is only one train in the station it will come out as an object and not an array. How can I make it convert everything to an array even if there is only one train coming.
public function getStationsByName(Request $request)
{
try {
$stationName = $request->input('id');
$url = "http://api.irishrail.ie//realtime/realtime.asmx/getStationDataByNameXML?StationDesc=";
$url .= $stationName;
$res['status'] = true;
$res['message'] = 'Success';
$ir = xmlparser::Parse($url);
$res ['results'] = json_decode($ir, TRUE);
$res['num_rows'] = count($res['results']);
return response($res, 200);
} catch (\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
This is what the data looks like with more than one train arriving at the station
And this is where there is only one arriving
You can check it by your self,
if(false !== ($result = json_decode($ir, TRUE))){
if(isset($result["objStationData"]["Servertime"])){
$objStationDatas = [$result["objStationData"]];
}else{
$objStationDatas = $result["objStationData"];
}
}