I want to retrieve the last 10 messages from gmail account and display them in a page. I have the following so far:

<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
/* connect to gmail */
$user = '****@gmail.com';
$password = '******';
$mailbox = "{imap.gmail.com:993/imap/ssl}INBOX";

?>

<?php
$mbx = imap_open($mailbox , $user , $password);
$sorted = imap_sort($mbx,SORTDATE, 1);

print_r($sorted);



/* grab emails */
$emails = imap_search($mbx, 'SINCE "10 Feb 2015"');

/* if emails are returned, cycle through each... */
if($emails) {

/* begin output var */
$output = '';


?>

<table class="table table-bordered table-hover">

 <tr> 
        <th>From</th>
        <th>Date</th>
        <th>Subject</th>
 </tr>

<?php    




/* for every email... */
foreach($emails as $email_number) {
   /* get information specific to this email */
    $overviews = imap_fetch_overview($mbx,$email_number,0);



?>


<?php
 /* put the newest emails on top.Doesnt work.*/
 //   rsort($overviews);

 print_r($overviews);
foreach($overviews as $overview)
{
?>



 <tr>
      <td><?php echo $overview->from; ?></td>
      <td><?php echo $overview->date; ?></td>
      <td><a href="open.php?id=<?php echo $overview->uid; ?>"><?php echo $overview->subject; ?></a></td>
 </tr>
 <?php

   }
 }     

}
?>
</table>

</body>
</html>

I see a post here but I'm having a hard time understanding how the poster is using variables $date & $search_criteria to get at solving the problem. I see how imap_sort returns an array of msgnos but having a hard making the leap to how I can use $sorted[] to then print out last 10 sorted emails by date.Thanks for any input

    You can use [man]usort[/man] for finer control over how array elements are sorted (for example by comparing their [font=monospace]date[/font] properties). To keep only the most recent ten you can [man]array-slce[/man] the sorted list.

      Thanks I have this :
      / put the newest emails on top./

      usort($overviews, function($a1, $a2) {
      $v1 = strtotime($a1['date']);
      $v2 = strtotime($a2['date']);
      return $v1 - $v2; // $v2 - $v1 to reverse direction
      });
      which works except I want it in descending order but when I swap $v1 & $v2 there is no change . Any thoughts on what might be wrong?

        10 days later

        Are you sure $a1 and $a2 are arrays and have a "date" member defined? You might want to try debugging your code or using some echo statements to see what values are getting passed to your sort function.

          5 years later

          Ajay1234 As this is a thread from 2015, and the OP has not posted since then, don't hold your breath awaiting a reply.

          Write a Reply...