Page 1 of 1

How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 8:11 am
by sathya
Here is my php code ,i have passed the train number and date inside the php code,

Code: Select all

<!DOCTYPE html>
<HTML>
  <HEAD>
    <META charset="utf-8">
  <meta name="description" content="live train running status provided from the indian railways database.you can check the irctc pnr status,live train status and train time tables,erail,railneer,spot your train">
    <meta name="keywords" content="live train status,live train running status,train running status,train current running status live,spot your train,national train enquiry system,train running information,current train running status,train running status live,current status of train,indian railway train status,train running current status,live status of train,irctc train running status,railway running status">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
    <TITLE>Train Status Time Table</TITLE>
 <style>
table {
    width:60%;
}
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;
}
table#t01 tr:nth-child(even) {
    background-color: white;
width:60%;

}
table#t01 tr:nth-child(odd) {
   background-color:white;
}
table#t01 th	{
    background-color: blue;
    color: white;
}
table#t02 th	{
    background-color: blue;
    color: white;
}
body {
    background-color: lightblue;
}
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
    width: auto;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #111;
}

.active {
    background-color: #4CAF50;
}
</style>
</head>
<body>
<center><h2><b>Live Train Running Status</b></h2></center>
<ul>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">Live Train Status</a></li>
  <ul style="float:right;list-style-type:none;">
    <li><a href="#about">Blog</a></li>
    <li><a href="#login">Contact</a></li>
  </ul>
</ul>
</br>
<center>
<?php
  $json = '';
  if(isset($_GET['trainnumber']) && (isset($_GET['doj']))) { 
    $url = 'http://api.railwayapi.com/live/train/'.$_GET['trainnumber'].'/doj/'.$_GET['doj'].'/apikey/*//';
	$url_trainname = 'http://api.railwayapi.com/name_number/train/'.$_GET['trainnumber'].'/apikey/*/';
$json = json_decode(file_get_contents($url), true);

$json_trainname = json_decode(file_get_contents($url_trainname), true);

$trainname=$json_trainname ['train']['name'];

$trainnumber = $json['train_number'];

$doj = $json['route'][0]['scharr_date'];

$position = $json['position'];
echo "<table id='t01'>";
  echo "<tr>";
    echo "<th><center>Train Number<center></th>";
    echo "<th><center>Date on Journey<center></th>";
  echo "</tr>";
echo "<table id='t01'><tr><td><center>$trainnumber<center></td><td><center>$doj<center></td></tr></table>";
echo "<table id='t01'>";
echo "<tr>";
    echo "<th><center>Position<center></th>";
  echo "</tr>";
echo "<table id='t01'><tr><td><center>$trainname  $position<center></td></tr></table>";
echo "<table id='t01' >";
echo "<tr>";
    echo "<th><center>Train Name<center></th>";
  echo "</tr>";
echo "<table id='t01'><tr><td><center>$trainname<center></td></tr></table>";
echo "<table id='t01'>";
  echo "<TR><TH><center>Station<center><TH><center>Scheduled<center><TH><center>Actual<center><TH><center>Status/Delay";
    foreach($json['route'] as $stop) {

	$url_trainnameconvert= 'http://api.railwayapi.com/name_number/train/'.$stop['station'].'/apikey/*/'; //passing the station element from Json Response 1 to Json Response 2
	$json_trainnameconvert = json_decode(file_get_contents($url_trainnameconvert), true);
	
	foreach($json_trainnameconvert['train'] as $trainnameconvert)
	{

	($stop['has_arrived'] === true) ? $stop['has_arrived'] = "Arrived" : $stop['has_arrived'] = "Still not here yet!";

      echo ' <TR><TD><center>'.$trainnameconvert['name'].'<TD><center>'.$stop['scharr'].'<TD><center>'.$stop['actarr'].'<TD><center>'.$stop['has_arrived']."\n"; //printing the '.$trainnameconvert['name'].' using echo to print the train name and station code here.
	  
	  }
	} 
  }
  else {
    echo "Something went wrong, please notify to admin [support@livetrainrunningstatus.co.in]";
  }
?>
  </TABLE>
 </BODY>
</HTML>
My Json Response 1:
{
"response_code": 200,
"error": "",
"position": "Train has reached Destination and late by 5 minutes.",
"train_number": "12046",
"route": [
{
"no": 1,
"station": "CDG",
"has_arrived": false,
"has_departed": true,
"day": 0,
"distance": 0,
"scharr": "Source",
"schdep": "12:00",
"actarr": "00:00",
"actdep": "12:00",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 0
},
{
"no": 2,
"station": "UMB",
"has_arrived": true,
"has_departed": true,
"day": 0,
"distance": 67,
"scharr": "12:40",
"schdep": "12:42",
"actarr": "12:40",
"actdep": "12:42",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 0
},
{
"no": 3,
"station": "KUN",
"has_arrived": true,
"has_departed": true,
"day": 0,
"distance": 142,
"scharr": "13:36",
"schdep": "13:38",
"actarr": "13:57",
"actdep": "13:59",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 21
},
{
"no": 4,
"station": "NDLS",
"has_arrived": true,
"has_departed": false,
"day": 0,
"distance": 265,
"scharr": "15:25",
"schdep": "Destination",
"actarr": "15:30",
"actdep": "00:00",
"scharr_date": "19 Nov 2015",
"actarr_date": "19 Nov 2015",
"latemin": 5
}
]
}
Json Response 2:
{
"response_code": 200
"train": {
"number": "12155",
"name": "BHOPAL EXPRESS"
"days": [
{
"day-code": "SUN",
"runs": "Y"
},
{
"day-code": "MON",
"runs": "Y"
},
{
"day-code": "TUE",
"runs": "Y"
},
{
"day-code": "WED",
"runs": "Y"
},
{
"day-code": "THU",
"runs": "Y"
},
{
"day-code": "FRI",
"runs": "Y"
},
{
"day-code": "SAT",
"runs": "Y"
}
],
},
}
I want the output like the below :

Train Name Station Code Scheduled Arrival Actual Arrival

if u have any queries kindly post here.

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 8:24 am
by Celauran
What have you tried?

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 8:30 am
by sathya
i tried the first foreach loop to get the station code then posting the station code to the url

then decoded the array values from json response

again i have printed the decoded json response2 array elements and print the station name using the next foreach loop,

but getting the error as undefined values ,invalid argument in foreach loop

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 11:39 am
by Christopher
Post the code. It is difficult to find a problem from an explanation of the code.

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 12:31 pm
by Celauran
Also, you're looking for $_GET['trainnumber'] and $_GET['doj']. Sample values for both would be handy. I saw one for trainnumber but nothing for doj

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 7:35 pm
by sathya
Hey see here below code,it's already there

Code: Select all

if(isset($_GET['trainnumber']) && (isset($_GET['doj']))) { 
    $url = 'http://api.railwayapi.com/live/train/'.$_GET['trainnumber'].'/doj/'.$_GET['doj'].'/apikey/*//';


I want to pass the station code in the url.

I will get station code in the foreach loop only
$stop[station] have the station code .

I can't pass the station code in the url below
my php code ,i have passed the train number and date inside the php code,

Code: Select all

<!DOCTYPE html>
<HTML>
  <HEAD>
    <META charset="utf-8">
  <meta name="description" content="live train running status provided from the indian railways database.you can check the irctc pnr status,live train status and train time tables,erail,railneer,spot your train">
    <meta name="keywords" content="live train status,live train running status,train running status,train current running status live,spot your train,national train enquiry system,train running information,current train running status,train running status live,current status of train,indian railway train status,train running current status,live status of train,irctc train running status,railway running status">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
    <TITLE>Train Status Time Table</TITLE>
 <style>
table {
    width:60%;
}
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
th, td {
    padding: 5px;
    text-align: left;
}
table#t01 tr:nth-child(even) {
    background-color: white;
width:60%;

}
table#t01 tr:nth-child(odd) {
   background-color:white;
}
table#t01 th    {
    background-color: blue;
    color: white;
}
table#t02 th    {
    background-color: blue;
    color: white;
}
body {
    background-color: lightblue;
}
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
    width: auto;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover:not(.active) {
    background-color: #111;
}

.active {
    background-color: #4CAF50;
}
</style>
</head>
<body>
<center><h2><b>Live Train Running Status</b></h2></center>
<ul>
  <li><a class="active" href="#home">Home</a></li>
  <li><a href="#news">Live Train Status</a></li>
  <ul style="float:right;list-style-type:none;">
    <li><a href="#about">Blog</a></li>
    <li><a href="#login">Contact</a></li>
  </ul>
</ul>
</br>
<center>
<?php
  $json = '';
  if(isset($_GET['trainnumber']) && (isset($_GET['doj']))) { 
    $url = 'http://api.railwayapi.com/live/train/'.$_GET['trainnumber'].'/doj/'.$_GET['doj'].'/apikey/*//';
        $url_trainname = 'http://api.railwayapi.com/name_number/train/'.$_GET['trainnumber'].'/apikey/*/';
$json = json_decode(file_get_contents($url), true);

$json_trainname = json_decode(file_get_contents($url_trainname), true);

$trainname=$json_trainname ['train']['name'];

$trainnumber = $json['train_number'];

$doj = $json['route'][0]['scharr_date'];

$position = $json['position'];
echo "<table id='t01'>";
  echo "<tr>";
    echo "<th><center>Train Number<center></th>";
    echo "<th><center>Date on Journey<center></th>";
  echo "</tr>";
echo "<table id='t01'><tr><td><center>$trainnumber<center></td><td><center>$doj<center></td></tr></table>";
echo "<table id='t01'>";
echo "<tr>";
    echo "<th><center>Position<center></th>";
  echo "</tr>";
echo "<table id='t01'><tr><td><center>$trainname  $position<center></td></tr></table>";
echo "<table id='t01' >";
echo "<tr>";
    echo "<th><center>Train Name<center></th>";
  echo "</tr>";
echo "<table id='t01'><tr><td><center>$trainname<center></td></tr></table>";
echo "<table id='t01'>";
  echo "<TR><TH><center>Station<center><TH><center>Scheduled<center><TH><center>Actual<center><TH><center>Status/Delay";
    foreach($json['route'] as $stop) {

        $url_trainnameconvert= 'http://api.railwayapi.com/name_number/train/'.$stop['station'].'/apikey/*/'; //passing the station element from Json Response 1 to Json Response 2
        $json_trainnameconvert = json_decode(file_get_contents($url_trainnameconvert), true);
        
        foreach($json_trainnameconvert['train'] as $trainnameconvert)
        {

        ($stop['has_arrived'] === true) ? $stop['has_arrived'] = "Arrived" : $stop['has_arrived'] = "Still not here yet!";

      echo ' <TR><TD><center>'.$trainnameconvert['name'].'<TD><center>'.$stop['scharr'].'<TD><center>'.$stop['actarr'].'<TD><center>'.$stop['has_arrived']."\n"; //printing the '.$trainnameconvert['name'].' using echo to print the train name and station code here.
          
          }
        } 
  }
  else {
    echo "Something went wrong, please notify to admin [support@livetrainrunningstatus.co.in]";
  }

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 11:41 pm
by Christopher
I am confused. What does not work? Is it:

Code: Select all

        $url_trainnameconvert= 'http://api.railwayapi.com/name_number/train/'.$stop['station'].'/apikey/irhzy1446/'; //passing the station element from Json Response 1 to Json Response 2

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 13, 2016 11:59 pm
by sathya
its working fine and leave all the things bro.but i want only one small help.

I have an array like the below:

Code: Select all

{
    "response_code": 200, 
    "stations": [
        {
            "lng": 83.3731675, 
            "lat": 26.7605545, 
            "code": "GKP", 
            "state": "Uttar Pradesh", 
            "fullname": "Gorakhpur Jn"
        }, 
        {
            "lng": 83.5842775, 
            "lat": 26.6492695, 
            "code": "CC", 
            "state": "Uttar Pradesh", 
            "fullname": "Chauri Chaura"
        }, 
        {
            "lng": 83.2142269, 
            "lat": 26.758544, 
            "code": "SWA", 
            "state": "Uttar Pradesh", 
            "fullname": "Sahjanwa"
        }, 
        {
            "lng": 83.3742644, 
            "lat": 26.7401226, 
            "code": "DDP", 
            "state": "Uttar Pradesh", 
            "fullname": "Daudpur"
        }
    ]
}
I want to get the full name element only.
"fullname": "Gorakhpur Jn"
can u pls suggest the code in general with foreach loop.

i know its only one value we can declare the value and print simply ,but i want in foreach loop.

Re: How to handle the two foreach loops in php?

Posted: Thu Jan 14, 2016 10:10 am
by Christopher
In the JSON below, the entire response is an object with two properties: response_code and stations. The stations property is an array of objects, each with five properties.

It is very important that you understand what is in the variables you are using. User var_dump(), print_r() or a debugger to understand your variables.

Here is code so you can see what the JSON is converted to. I show it with and without the associative array parameter set to true.

Code: Select all

$json = <<<JSON
{
    "response_code": 200, 
    "stations": [
        {
            "lng": 83.3731675, 
            "lat": 26.7605545, 
            "code": "GKP", 
            "state": "Uttar Pradesh", 
            "fullname": "Gorakhpur Jn"
        }, 
        {
            "lng": 83.5842775, 
            "lat": 26.6492695, 
            "code": "CC", 
            "state": "Uttar Pradesh", 
            "fullname": "Chauri Chaura"
        }, 
        {
            "lng": 83.2142269, 
            "lat": 26.758544, 
            "code": "SWA", 
            "state": "Uttar Pradesh", 
            "fullname": "Sahjanwa"
        }, 
        {
            "lng": 83.3742644, 
            "lat": 26.7401226, 
            "code": "DDP", 
            "state": "Uttar Pradesh", 
            "fullname": "Daudpur"
        }
    ]
}
JSON;

$station_data = json_decode($json);
echo "<pre>" . print_r($station_data, 1) . "</pre>";

foreach($station_data->stations as $station) {
     echo $station->fullname . '<br>';
}

$station_data = json_decode($json, true);          // true to return objects as associative arrays
echo "<pre>" . print_r($station_data, 1) . "</pre>";

foreach($station_data['stations'] as $station) {
     echo $station['fullname'] . '<br>';
}

Re: How to handle the two foreach loops in php?

Posted: Thu Jan 14, 2016 10:27 am
by sathya
Yes you are correct ,it will print the first value in that mentioned array.

thank you so much for your help.

Re: How to handle the two foreach loops in php?

Posted: Wed Jan 20, 2016 4:48 am
by sathya
when execute the code provided by you getting same results but print r display how the array values displayed in structured view.