dongtou2016 2013-09-16 23:24
浏览 27
已采纳

PHP:数组的内部指针在最后一个元素之前停止一个元素 - 很奇怪

I have a simple multidimensional array. I modify it - ie. I add data to it - in a foreach loop, accessing its elements by reference:

 $array = array(
    array('id' => 12, 'name' => 'John1', 'surname' => 'Smith1'),
    array('id' => 13, 'name' => 'John2', 'surname' => 'Smith2'),
    array('id' => 14, 'name' => 'John3', 'surname' => 'Smith3'),
    array('id' => 15, 'name' => 'John4', 'surname' => 'Smith4'),
 );

 foreach($array as &$a) {
    $a['middlename'] = 'Robert';
 }

Now what's below shows that $array is perfectly in order:

print('<pre>'.print_r($array,true).'</pre>'); results in:

    Array
    (
        [0] => Array
            (
                [id] => 12
                [name] => John1
                [surname] => Smith1
                [middlename] => Robert
            )

        [1] => Array
            (
                [id] => 13
                [name] => John2
                [surname] => Smith2
                [middlename] => Robert
            )

        [2] => Array
            (
                [id] => 14
                [name] => John3
                [surname] => Smith3
                [middlename] => Robert
            )

        [3] => Array
            (
                [id] => 15
                [name] => John4
                [surname] => Smith4
                [middlename] => Robert
            )

    )

But while I loop though it, internal pointer stops right before last element:

 foreach($array as $a) {
     print('<pre>'.print_r($a['id'],true).'</pre>');
 }

outputs:

 12
 13
 14
 14

Any hints what's going on?

UPDATE: The answer I picked is correct and moreover I found this: PHP Pass by reference in foreach Thx, SO.

  • 写回答

2条回答 默认 最新

  • doumu1212 2013-09-16 23:31
    关注

    I've had a similar issue, when modifying an array with a foreach and then accessing the array afterwards. My guess is that you are not destroying the reference after you loop through, and are overwriting the value accidentally. Try unset($a); after your foreach.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思