【问题标题】:Assigning by reference an array returned by a method call in PHP?通过引用分配由 PHP 中的方法调用返回的数组?
【发布时间】:2012-07-31 14:22:04
【问题描述】:

我需要循环每个$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

【问题讨论】:

    标签: php arrays variable-assignment


    【解决方案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);
    

    【讨论】:

    • 注意$recipient前的&,它将通过引用传递而不是复制
    • 当前元素通过引用传递,整个数组被复制。那就是数组没有被修改。刚刚测试...
    • 你试过了还是不行?因为我一直这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2011-07-18
    • 2021-12-21
    • 2021-06-30
    • 2012-03-21
    • 2018-10-18
    相关资源
    最近更新 更多