2012-08-02 64 views
0

我需要在每個$message收件人環(收件人是array),如果出現錯誤,unset相應的收件人:通過引用分配由PHP中的方法調用返回的數組?

$recipients = &$message->getRecipients(); // array 

// Do this now as arrays is going to be altered in the loop 
$count = count($recipients);   

for($i = 0; $i <= $count; $i++): 

    $response = $messageManager->send($recipients[$i], $content); 

    // If not 200 OK remove the recipient from the message 
    if($response->getStatusCode !== 200) unset($recipients[$i]); 

endfor; 

但是PHP不會讓我這樣做,因爲「只有變量通過參考分配「。有什麼我可以重新分配陣列做,除了:

$recipients = $message->getRecipients(); 

// Loop 

$message->setRecipients($recipients); 

編輯:不能使用的foreach和通過引用傳遞當前元素:

$recipients = array('a', 'b', 'c'); 

foreach($recipients as &$recipient) 
    unset($recipient); 

echo count($recipients); // 3 

回答

-1

你可以這樣做而不是:

$recipients = $message->getRecipients();  

foreach($recipients as $key => $recipient) : 

    $response = $messageManager->send($recipient, $content); 
    if($response->getStatusCode !== 200) unset($recipients[$key]); 

endforeach; 

$message->setRecipients($recipients); 
+0

不,如'foreach'進行復印... – Polmonino 2012-08-02 15:20:40

+0

注$收件人的&,它會按引用傳遞它,而不是複製 – Oussama 2012-08-02 15:21:48

+0

銅rrent元素通過引用傳遞,整個數組被複制。這是數組未被修改。剛剛測試過... – Polmonino 2012-08-02 15:24:25