通过引用分配PHP中的方法调用返回的数组?

时间:2012-08-02 15:05:06

标签: php arrays variable-assignment

我需要循环每个$message收件人(收件人是array),如果出现问题,unset相应的收件人:

$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 个答案:

答案 0 :(得分:-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);