For the given results you can do the following. But extending for 4000 records, you may need to look for some query manipulation.
Plz, check the date comparison part as i may not be correct by the PHP syntax and function. But this can be used as a general concept.
<?php
$host = "servername\instancename";
$connectionInfo = array( "Database"=>"AccessCard", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
/**********************************************/
$FRISTsql = "SELECT [EmpID],[DATE],[TIME],[OBJECT] FROM [AccessCard].[dbo].[TimeAtt] WHERE [EmpID]='E003' order by [DATE],[TIME]";
$Fstmt = sqlsrv_query( $conn, $FRISTsql );
if( $Fstmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
else {
$enterTime; $exitTime;
while( $Frow = sqlsrv_fetch_array( $Fstmt, SQLSRV_FETCH_ASSOC) ) {
$R1 = $Frow['EmpID'];
$R2 = $Frow['DATE']->format('Y-m-d');
$R3 = $Frow['TIME']->format('H:i:s');
$R4 = $Frow['OBJECT'];
if($enterTime == null && $R4 == 2001)
{
$enterTime = $R3;
}
if($exitTime == null && $R4 == 2002)
{
$exitTime = $R3;
}
else if($R3 < $enterTime && $R4 == 2001)
{
$enterTime = $R3;
}
else if($R3 > $exitTime && $R4 == 2002)
{
$exitTime = $R3;
}
ECHO $R1."   ";
ECHO $R2."    ";
ECHO $R3."    ";
ECHO $R4."</BR> ";
}
ECHO "User:".$R1." for date".$R2." worked for ".($exitTime - $enterTime);
}
sqlsrv_free_stmt( $Fstmt);