drk49438 2015-08-03 15:39
浏览 323
已采纳

无法访问if语句之外的全局数组?

I am having some issues with setting a global array in php. The data I get from $_POST is straight from my database. I sent it through an external page to JSON decode/etc. (that part works, so I didnt paste the code). I only want to do this if data is set, then I want to take that array and do other things with it throughout the rest of my code. The problem I am having is the array outside of the if statement is null. I can't seem to figure out why? If I were to echo a var_dump inside the if statement, the values are inside the GLOBALS['Array']

 function is_assoc($array) {
   foreach (array_keys($array) as $k => $v) {
     if ($k !== $v)
      return true;
     }
     return false;
   }

$GLOBALS['Array'] = array(); 

if (isset($_POST['data'])) {
   $Data = $_POST['data'];

   $decode = new JSONdecoder($Data);
   $decode->decodeNew($Data);
   $Data = $decode->decodedArray;

   $decryptor = new DataDecryptor(base64_decode($_POST['key']), $_POST['tracking'], $hostName);
   $decodedData =  $decryptor->decrypt_arr($Data);

   foreach($decodedData as $key => $val){
      if(is_assoc($val)){
         foreach($val as $key2 => $val2){
            $theArray[$key2] = $val2;
         }      
      }else{
         $theArray[$key] = $val;
      }
    }

 $GLOBALS['Array'] = $theArray;
}
echo var_Dump($Array);
  • 写回答

1条回答 默认 最新

  • duancong7573 2015-08-04 05:08
    关注

    Your issue is somewhere else. $GLOBALS is a superglobal variable accessible from any scope.

    When you define a new entry in $GLOBALS, it automatically creates a variable holding the same name, but that variable is only visible in that particular scope. If you are in another scope and you want to initialize that as a variable, you need to use the global keyword : global $var; (look at the code below for an example - inside the test() function).

    Are you sure 100% that you are always doing the same tests (Are you 100% positive that when testing, you are always entering the foreach statement?)

    To clarify the behavior of $GLOBALS:

    <?php
    
    $GLOBALS['foo'] = 'bar';
    
    var_dump($foo); // outputs 'bar'
    
    if (true) {
        $GLOBALS['foo'] = 'bar2';
    }
    
    var_dump($foo); // outputs 'bar2'
    
    function test() {
        var_dump($foo); // notice undefined variable - outputs NULL
        var_dump($GLOBALS['foo']); // outputs 'bar2'
        global $foo;
        var_dump($foo); // outputs 'bar2';
    }
    
    test();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?