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

通过引用分配PHP中方法调用返回的数组?,php,arrays,variable-assignment,Php,Arrays,Variable Assignment,我需要循环每个$message收件人(收件人是数组),如果出现问题,取消设置相应的收件人: $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++): $resp

我需要循环每个
$message
收件人(收件人是
数组
),如果出现问题,
取消设置相应的收件人:

$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;
编辑:无法使用foreach并通过引用传递当前元素:

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

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

echo count($recipients); // 3

您可以这样做:

$recipients = $message->getRecipients();      

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

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

endforeach;

$message->setRecipients($recipients);

注意,$recipient之前,它将通过引用传递它,而不是copyCurrent元素通过引用传递,整个数组将被复制。也就是说,数组没有被修改。刚刚测试过…你有没有试过,但不起作用?因为我一直都这么做
$recipients = $message->getRecipients();      

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

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

endforeach;

$message->setRecipients($recipients);