在不同的foreach子句之间传递全局值

时间:2014-02-04 14:48:24

标签: php arrays multidimensional-array

看看以下数组

$all  = $ent->getAll($code); 
// This code generates the following array
    Array ( 
        [LN] => Array (
            [106] => table,
            [110] => pen,
            [132] => book,
        )
    )

    $select  = $ent->getSelected($code); 
    // This code generates the following array
    Array (
        [LN] => Array (
            [110] => pen,
            [132] => book,
        )
    )

我需要做的是,如果在$select中找到$all放入全局$valt变量并取消设置,那么在下一个foreach子句中不要包括上述值。请看下面的代码......

global $valt;
foreach ($all as $orgKey => $list) {
        foreach ($list as $key=>$val) { 
            global $valt;

            $selected1 = isset($select[$orgKey][$key]) ? $key : '';
            $valt = $selected1;

            // This is printing correct "pen"
            echo $valt;
        }
    }      

    echo $valt; // This print doesn't show any thing why? 



foreach ($all as $orgKey => $list) {
            foreach ($list as $key=>$val) { 
                global $valt;

                $selected2 = isset($select[$orgKey][$key]) ? $key : '';
                $valt = $selected2;

                // This is printing still the same value like above, but i expect "book"
                echo $valt;
            }
        }   

怎么解决?

1 个答案:

答案 0 :(得分:-1)

嗯..

也许你可以尝试使用函数..

$foo = "bar";
function updateglobal(){
     global $foo;

     if(1>0){
      $foo = "newbar";
     }
}