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

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

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条)

报告相同问题?