有没有人见过这种情况发生在php foreach循环中?

时间:2013-07-17 21:59:52

标签: php multidimensional-array foreach

我从一个有101个键的查询中构建了一个多维数组

当我在某个foreach循环之前回显$ result ['q101']时,它会显示正确的数据..

在这个循环之后,数组被修改为$ result ['q101'] => 8 ... ???

注意:无论数字如何,这都发生在最后一个密钥上。

> [q99] => Array
>     (
>         [name] => Disentanglement from Love Relationship
>         [abbr] => DfLR
>         [type] => Ascending
>         [response] => Sometimes
>         [score] => 3
>     )
> 
> [q100] => Array
>     (
>         [name] => Feelings of Self Worth
>         [abbr] => FoSW
>         [type] => Ascending
>         [response] => Almost Always
>         [score] => 1
>     )
> 
> [q101] => 8 /// WTF is this..??

下面是罪魁祸首..如果我删除这一切都是hunky dory。

foreach ($result as $key => $val){
    $response_table .= '<tr><td>'.str_replace('q', '', $key).'</td><td>'.$val['response'].'</td><td>'.$val['abbr'].'</td><td>'.$val['type'].'</td><td>'.$val['score'].'</td></tr>';
    $min[$val['abbr']] += 1;
    $max[$val['abbr']] += 1;    
}

1 个答案:

答案 0 :(得分:4)

确保你在foreach之后取消$ key,$ val。 来自http://php.net/manual/en/control-structures.foreach.php 即使在foreach循环之后,$ value和最后一个数组元素的引用仍然存在。建议通过unset()来销毁它。

相关问题