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

array values assign inside function but shows empty outside

我正在 magento 网站上工作,当数组值在函数内部分配并在函数外部检索时遇到奇怪的错误。

//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);
}

我在另一个函数中调用这里的函数

$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);

任何人都知道如何解决这个问题,我试了几个小时都没有运气。谢谢

尝试推送而不是 assigning.Try 这个:

$ctall[][rand(10000,100000)]=$fg; //notice the empty square brackets

你也可以试试这个:

function printtest($fg){
  global $ctall;
  $new_array =array();
  $new_array[rand(10000,100000)] = $fg;
  array_merge($ctall, $new_array);
}

删除 $ctall 的所有声明,然后试试这个:

//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;
}

在外面,像这样倾倒:

var_dump($GLOBALS['ctall'])