2014-01-07 81 views
0

我使用PHP函數imap_open這個讓每封電子郵件的標題:PHP是否存在

$header=imap_headerinfo($inbox,$email_number); 

我然後運行在抄送電子郵件地址foreach循環:

foreach ($header->cc as $cc_extra) { 

} 

如何在運行foreach循環之前檢查$header->cc中是否有任何內容?

注: - 的$inbox是郵箱 連接字符串 - 該$email_number是每個電子郵件的電子郵件數量

+0

可能重複[最簡潔的方式來跳過一個foreach,如果數組是空的](http://stackoverflow.com/questions/3446538/cleanest-way-to-skip-a -foreach-IF-陣列是空) – adamdunson

回答

0

你可以使用和is_arrayisset組合,像這樣:

$header=imap_headerinfo($inbox,$email_number); 
// ... 
if(isset($header->cc) && is_array($header->cc)) { 
    foreach ($header->cc as $cc_extra) { 
    } 
} 

isset將測試變量已被設置爲不是null
is_array將測試該變量實際上是array

編輯

另外,如this SO answer看到的,你可以明確地投的變量作爲數組內的foreach,例如,

foreach ((array)$header->cc as $cc_extra) { 
} 
0

我用下面的代碼:

$connection = imap_open("{192.168.1.170:993/imap/ssl/novalidate-cert}INBOX", $send_from_our, $send_from_pass) or die('Cannot connect to your sever: ' . imap_last_error()); 
$emails = imap_search($connection, 'UNSEEN'); 
$unread = 0; 
$count = imap_num_msg($connection); 

for ($msgno = 1; $msgno <= $count; $msgno++) { 
    $cc=''; 
    $to=''; 
    $headers = imap_headerinfo($connection, $msgno);   
    if ($headers->Unseen == 'U') { 
     $unread++; 
     if (isset($headers->cc) && is_array($headers->cc)) { 
      foreach ($headers->cc as $cc_extra) { 
       $mailbox_cc=strtolower($cc_extra->mailbox); 
       $host_cc=strtolower($cc_extra->host); 
       $cc .= $mailbox_cc . "@" . $host_cc .','; 
      } 
      $cc= rtrim($cc, ','); 
     } 
     if (isset($headers->to) && is_array($headers->to)) { 
      foreach ($headers->to as $to_extra) { 
       $mailbox_to=strtolower($to_extra->mailbox); 
       $host_to=strtolower($to_extra->host); 
       if ($mailbox_to=='$MY_EMAIL_NAME' and $host_to='$MY_HOST_NAME') { 
        continue; 
       } 
       $to .=$mailbox_to . "@" . $host_to.','; 
      } 
      $to=rtrim($to, ','); 
     } 
     $fromaddr = $headers->from[0]->mailbox . "@" . $headers->from[0]->host; 
     $full_reply_to=rtrim($fromaddr.','.$cc.','.$to, ','); 

此代碼接收來自maibox的所有未讀郵件,並將所有來自CC和TO的地址(不包括我的自我地址)爲每個電子郵件$ full_reply_to