先简单的说明下吧:对于程序中的 $conf 先用 foreach() 引用形式处理了一下,接着用 foreach() 拷贝形式遍历了一下,之后问题就出来了:
在第二个 foreach() 前后输出这两个 foreach() 处理过的变量,没有达到目的, $conf[‘friends'] 的一个键被省略了,为什么这样怎么想也没想出来;请大家看代码:
$conf = array(
'friends' => array(
array(
'uid' => 1,
'name' => 'hello',
),
array(
'uid' => 2,
'name' => 'world',
),
array(
'uid' => 3,
'name' => 'who am i?',
),
array(
'uid' => 4,
'name' => 'spider-man'
)
),
);
foreach($conf['friends'] as &$user){
if (!isset($user['size'])){
$user['size'] = 12;
}
}
//unset($user);$friends = array();print_array($conf['friends']);foreach($conf['friends'] as $user){
$friends[$user['uid']] = $user['name'].'------->ookong.com';
}print_array($friends);function print_array($arr, $type = 1){
if (is_array($arr)){
if ($type === 0){
echo '<pre>';
var_dump($arr);
echo '</pre>';
}else{
echo '<pre>';
print_r($arr);
echo '</pre>';
}
}else{
echo '<br />not an array';
}}

解决方案 »

  1.   

    运行一下输出是这样的:
    Array
    (
        [0] => Array
            (
                [uid] => 1
                [name] => hello
                [size] => 12
            )    [1] => Array
            (
                [uid] => 2
                [name] => world
                [size] => 12
            )    [2] => Array
            (
                [uid] => 3
                [name] => who am i?
                [size] => 12
            )    [3] => Array
            (
                [uid] => 4
                [name] => spider-man
                [size] => 12
            ))Array
    (
        [1] => hello------->ookong.com
        [2] => world------->ookong.com
        [3] => who am i?------->ookong.com
    )问题是:
    输出的第二个数组为什么 3 个元素,应该是 4 个的。但是在第一个和第二个 foreach() 之间用 unset($user) 之后就没有问题了,请问问什么???谢谢各位了.......
      

  2.   

    lz,你的问题和这个帖子的问题一样
    http://topic.csdn.net/u/20090626/09/7a397cc6-f3d7-4e70-b932-8df00746e173.html
    看我的回复。
      

  3.   

    foreach($conf['friends'] as &$user){
    这个不要用引用了,手册讲复杂数组用引用会出奇怪问题  不建议使用