douping1581 2018-01-25 10:55
浏览 62
已采纳

数组值在函数内部分配但在外部显示为空

I'm working on magento site and facing strange error when array values assign inside function and retrieve outside of function.

//define array
$ctall=array();
//function for array value assign
function printtest($fg){
//global variable
    global $ctall;

    //just assign to array
    $ctall[rand(10000,100000)]=$fg; 

 //this var dump shows array with vaues  when function calling
//  var_dump($ctall);
}

i call the function here inside an another function

$categoryTree = Mage::getResourceModel('catalog/category')->getCategories($categoryId, 0, true);
$printCategories = function($nodes) use (&$printCategories) {

   foreach ($nodes as $_category):
      $ctdf=$_category->getId();
      $categoryn = Mage::getModel('catalog/category')->load($ctdf);
          if($ctdf!='' && $categoryn->getIsActive()):
                //here call to function by passing a value
                printtest($ctdf);   
          $printCategories($_category->getChildren());       
        endif; 
  endforeach; 


};


$printCategories($categoryTree);

//sleep(10);



// i try to get array results here but it shows empty
var_dump($ctall);

Anyone know how to fix this, i tried hours without luck. Thank You

  • 写回答

2条回答 默认 最新

  • dsij89625 2018-01-25 11:30
    关注

    remove all declaration of $ctall, and try this:

    //remove define array, don't define it
    // $ctall=array();
    
    function printtest($fg){
    
        if(!isset($GLOBALS['ctall'])){
            $GLOBALS['ctall'] = array();
        }
        //assign to global
        $GLOBALS['ctall'][rand(10000,100000)]=$fg;
    }
    

    on outside, dump like this:

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法