&Array() - 更新数组后带有&符号的最终行

use*_*149 2 php arrays

我试图直接更新数组的某些值.这是完美的.我使用以下方法:

foreach( $items as &$item ) {
    if( $criteria == 'correct' ) {
      // update array
      $item['update_me'] = 'updated';
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我现在有一个名为$ items的更新数组.

但是,我遇到的问题是,当这个数组输出到屏幕时(通过另一个foreach循环),数组的最后一行丢失了.

如果我通过var_dump($ items)打印整个数组; 方法,我注意到每行都以Array(9)为前缀.然而最后一行以&Array(9)作为前缀 - 注意领先的&符号.我相信这很重要!但我不确定这意味着什么.为什么它只应用于数组的最后一行?我怎么摆脱它呢?

来自评论:

array(6) { 
    [0]=> array(9) { 
        ["item_id"]=> string(4) "1" 
        ["item_description"]=> string(9) "blah blah" 
        ["quantity"]=> string(1) "4" 
        ["unit_cost"]=> string(4) "5.00" 
        ["subtotal"]=> string(4) "20.00" 
    } 
    [1]=> &array(9) { 
        ["item_id"]=> string(4) "2" 
        ["item_description"]=> string(9) "blah blah" 
        ["quantity"]=> string(1) "1" 
        ["unit_cost"]=> string(4) "5.99" 
        ["subtotal"]=> string(4) "5.99" 
    } 
}
Run Code Online (Sandbox Code Playgroud)

ale*_*ods 11

你必须在循环后取消设置$ item.正确的代码:

foreach( $items as &$item ) {
    if( $criteria == 'correct' ) {
      // update array
      $item['update_me'] = 'updated';
    }
}
unset($item);
Run Code Online (Sandbox Code Playgroud)

&签入var_dump结果指定这是引用.您可以使用xdebug_zval_dump()函数进行检查:

xdebug_zval_dump($item)
Run Code Online (Sandbox Code Playgroud)

你会看到is_ref = true.在PHP中,这意味着有指向相同的zval容器另一个变量(什么是zval的?看这里http://php.net/manual/en/internals2.variables.intro.php).如果您正在使用&in循环,则必须始终在循环后取消设置引用以避免难以检测的错误.


Ano*_*ode 5

我不确定这里是否是这种情况,但是如果在循环之后没有设置引用(在手册中有关于它的警告),则已知引用的foreach循环会导致这类问题.尝试unset($item);在更新foreach完成后立即添加,看看它是否解决了问题.